¿Cómo llamo a mis propias implementaciones de miembros de la interfaz?

programación


Estoy intentando crear una clase (Medición) que debería imitar las clases numéricas internas de C# (En t, doble, flotar, etc) lo más cerca posible. Para ello he definido el Medición clase para tener sus propias implementaciones de los métodos utilizados por las clases de C#.

Sin embargo, tengo problemas para acceder a las nuevas implementaciones. El siguiente ejemplo de código muestra la sintaxis que estoy usando.

Mi clase incluye lo siguiente para definir el PruebeConvertFromChecked() método:

C#
public partial class Measurement<T> : ..., INumberBase<Measurement<T>>,...
        where T : ...,INumberBase<T>, ...
    {
...
        /// <inheritdoc cref="INumberBase{TSelf}.TryConvertFromChecked{TOther}(TOther, out TSelf)" />
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        static bool INumberBase<Measurement<T>>.TryConvertFromChecked<TOther>(TOther value, [MaybeNullWhen(false)] out Measurement<T> result)
        {
            return TryConvertFrom(value, out result, ConversionOption.Checked);
        }

        private static bool TryConvertFrom<TOther>([NotNull] TOther value, [MaybeNullWhen(false)] out Measurement<T> result, ConversionOption option)
            where TOther : INumberBase<TOther>
        {
            ...
        }
...
    }

Y estoy tratando de llamar a ese método de la siguiente manera:

C#
if (!T.TryConvertFromChecked(toUnit.CompoundFactor, out var toCompoundFactor))
    {
        throw new ApplicationException($"An internal error occurred while converting the CompoundFactor for [{unitSymbol}] from type [{toUnit.CompoundFactor}] to type [{typeof(T)}]");
    }

Pero esto siempre está ejecutando el C# interno. System.Numerics.INumberBase implementación. ¿Cómo recibiría mi llamada? PruebeConvertFromChecked() ¿Cómo llamar al que he creado?

Lo que he probado:

C#
if (!T.Measurement<T>.TryConvertFromChecked(toUnit.CompoundFactor, out var toCompoundFactor))

Resultados en CS0704 No se puede realizar una búsqueda de miembros no virtuales en ‘T’ porque es un parámetro de tipo

Solución 1

Aquí está tu problema:

C#
T.TryConvertFromChecked(toUnit.CompoundFactor, out var toCompoundFactor)

Esto llama la TryConvertFromChecked en el readonly struct Double. Aquí está el método:

C#
static bool INumberBase<double>.TryConvertFromChecked<TOther>(TOther value, out double result)
{
    return TryConvertFrom<TOther>(value, out result);
}

y el TryConvertFrom:

C#
private static bool TryConvertFrom<TOther>(TOther value, out double result)
    where TOther : INumberBase<TOther>
{
    // In order to reduce overall code duplication and improve the inlinabilty of these
    // methods for the corelib types we have `ConvertFrom` handle the same sign and
    // `ConvertTo` handle the opposite sign. However, since there is an uneven split
    // between signed and unsigned types, the one that handles unsigned will also
    // handle `Decimal`.
    //
    // That is, `ConvertFrom` for `double` will handle the other signed types and
    // `ConvertTo` will handle the unsigned types

    if (typeof(TOther) == typeof(Half))
    {
        Half actualValue = (Half)(object)value;
        result = (double)actualValue;
        return true;
    }
    else if (typeof(TOther) == typeof(short))
    {
        short actualValue = (short)(object)value;
        result = actualValue;
        return true;
    }
    else if (typeof(TOther) == typeof(int))
    {
        int actualValue = (int)(object)value;
        result = actualValue;
        return true;
    }
    else if (typeof(TOther) == typeof(long))
    {
        long actualValue = (long)(object)value;
        result = actualValue;
        return true;
    }
    else if (typeof(TOther) == typeof(Int128))
    {
        Int128 actualValue = (Int128)(object)value;
        result = (double)actualValue;
        return true;
    }
    else if (typeof(TOther) == typeof(nint))
    {
        nint actualValue = (nint)(object)value;
        result = actualValue;
        return true;
    }
    else if (typeof(TOther) == typeof(sbyte))
    {
        sbyte actualValue = (sbyte)(object)value;
        result = actualValue;
        return true;
    }
    else if (typeof(TOther) == typeof(float))
    {
        float actualValue = (float)(object)value;
        result = actualValue;
        return true;
    }
    else
    {
        result = default;
        return false;
    }
}

La conversión no está abierta a la personalización de la manera que desee. sería mejor que consideraras usar el Clase TypeConverter (System.ComponentModel) | Microsoft aprende[^]

Sin embargo, si aún deseas seguir este camino, echa un vistazo a Navegador de código fuente .NET – BigInteger[^] para ver cómo lo aborda Microsoft.

コメント

タイトルとURLをコピーしました