【问题标题】:How to perform math operations with generic variables?如何使用泛型变量执行数学运算?
【发布时间】:2015-08-15 07:55:00
【问题描述】:

我正在处理一个需要整数的字符串表示形式的项目,但使用 .NET Framework 本身不支持的奇数基数(据我所知) - 例如 base36、62、64 等。
我们决定编写一个适用于任何数字基数的整体字符串转换系统,因为它是一个足够简单的操作。

稍后,我们希望创建一个自定义 IFormatProvider/ICustomFormatter 以使其更易于使用。
但首先,我们想解决转换过程本身,以一些执行转换并返回一些基本结果的静态方法的形式。
一旦我们得到这个工作,我们将把 IFormatProvider 包装器放在适当的位置。

我已经有一段时间没有使用 C# 泛型了,我不记得如何让编译器对这个操作感到满意。
我更愿意创建一个私有静态泛型 ConvertInteger 方法,然后我可以从公共静态 Convert 方法中调用该方法,以帮助强制执行强类型化,而不会使其使用混乱。
此设置的一个主要原因是在转换有符号值与无符号值时避免符号位出现问题。
现在,我们为 longulong 提供了公共静态 convert 方法,以帮助避免有符号值和无符号值之间的转换问题。
将来,假设我们可以让私有静态泛型方法工作,我们希望扩展公共方法以包括 int、uint、short、ushort、byte 和 sbyte 作为显式实现,以帮助提高执行时的性能大批量不同整数大小值的方法。
这是通用方法设计派上用场的地方,因此我们不必一遍又一遍地复制完全相同的代码(也使测试和调试变得更加简单)。

我遇到的问题是,编译器不允许我使用泛型类型执行比较或数学运算,因为它不知道如何执行操作之前提供了泛型类型参数值。
(这确实让我很恼火,主要是作为 C++ 开发人员,因为 C++ 通过简单地避免尝试解释泛型代码来解决这个问题,直到 提供类型参数值。)

我需要做什么才能让编译器对这种泛型方法设计感到满意?
我提供了下面的代码,cmets表示具体的编译错误。

public static class NumericStringConverter
{
    private static readonly string[] StandardDigits = new string[]
    {
        "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
        "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
        "_", "-"
    };



    private static string ConvertInteger<T>(T Value, T Base)
    {
        if (Base < 2) // error here: "Operator '<' cannot be applied to operands of type 'T' and 'int'"
            throw new ArgumentOutOfRangeException("Base", Base, "The NumericStringConverter.Convert(Value, Base) method was called, with the Base parameter set to a value less than 2.");

        if (Base > 64) // error here: "Operator '>' cannot be applied to operands of type 'T' and 'int'"
            throw new ArgumentOutOfRangeException("Base", Base, "The NumericStringConverter.Convert(Value, Base) method was called, with the Base parameter set to a value greater than 64.");

        if (Value == 0) // error here: "Operator '==' cannot be applied to operands of type 'T' and 'int'"
            return StandardDigits[0];

        string strResult = "";
        bool IsValueNegative = (Value < 0); // error here: "Operator '<' cannot be applied to operands of type 'T' and 'int'"

        while (Value != 0) // error here: "Operator '!=' cannot be applied to operands of type 'T' and 'int'"
        {
            strResult = strResult.Insert(0, StandardDigits[Math.Abs(Value % Base)]); // error here: "Operator '%' cannot be applied to operands of type 'T' and 'T'"
            Value /= Base; // error here: "Operator '/=' cannot be applied to operands of type 'T' and 'T'"
        }

        if (IsValueNegative)
            strResult = strResult.Insert(0, "-");

        return strResult;
    }



    public static string Convert(long Value, long Base)
    {
        return ConvertInteger<long>(Value, Base);
    }

    public static string Convert(ulong Value, ulong Base)
    {
        return ConvertInteger<ulong>(Value, Base);
    }

    public static T Convert<T>(string Value, T Base)
    {
        return default(T); // TODO: convert a string back into an integer value.
    }
}

【问题讨论】:

  • 没有只允许整数类型的通用约束——最好的限制是IConvertible,但它也允许浮点类型。我会泛化你能做的事情,并对不同的整数类型进行重载。
  • 为什么Base 必须是T?如果它只允许 2 到 64 之间的值,为什么它不能是 byte 或其他整数类型?
  • @DStanley 我们最初考虑过这一点,但发现如果我们保持相同的类型,Value % Base 和 Value /= Base 操作会更顺畅。
  • “平滑”以什么方式? long % bytelong /= byte 不应该需要强制转换或其他转换..
  • 您说“...帮助提高性能...”。我的建议是不要再担心性能,除非您有必须满足的真正性能指标并且您没有达到这些指标并且仔细分析告诉您这种转换是问题 then 你可以看看制作一个泛型方法是否有任何帮助。否则,只需使用适合您需要的最大类型和重载来回退。您正在将时间花在可能根本不重要的事情上。

标签: c# .net generics types


【解决方案1】:

因为你不能定义一个只允许整数类型的通用约束,我只需要一个适用于longs 的方法和一个适用于int 的重载:

private static string ConvertInteger(long Value, byte Base)
{
    if (Base < 2)
        throw new ArgumentOutOfRangeException("Base", Base, "The NumericStringConverter.Convert(Value, Base) method was called, with the Base parameter set to a value less than 2.");

    if (Base > 64) 
        throw new ArgumentOutOfRangeException("Base", Base, "The NumericStringConverter.Convert(Value, Base) method was called, with the Base parameter set to a value greater than 64.");

    if (Value == 0) 
        return StandardDigits[0];

    string strResult = "";
    bool IsValueNegative = (Value < 0); 

    while (Value != 0) 
    {
        strResult = strResult.Insert(0, StandardDigits[Math.Abs(Value % Base)]); 
        Value /= Base; 
    }

    if (IsValueNegative)
        strResult = strResult.Insert(0, "-");

    return strResult;
}
public static string Convert(int Value, byte Base)
{
    return ConvertInteger((long)Value, Base);
}

public static string Convert(ulong Value, byte Base)
{
    return ConvertInteger((long)Value, Base); // check for overflow?
}

【讨论】:

  • 是的,这是我们想要避免的溢出检查 - 容易出现错误,并且当 IMO 本身就足够强大的类型检查时会过于复杂。
  • 那么你必须有不同的方法来处理有符号和无符号类型。您不能支持在同一方法中同时支持 longulong 的范围,除非您只允许一个字节数组和其他一些指示它是否已签名的指标..
【解决方案2】:

C# 10 和 .NET 6:2021 年 11 月起的解决方案

好消息:现在 .NET 6 和 C# 10 中有一个解决方案,参见。 https://devblogs.microsoft.com/dotnet/preview-features-in-net-6-generic-math/#generic-math

为了执行数学运算,您可以接受任何数字类型INumber&lt;T&gt; 并指定所需的运算符,例如:

public T Adding<T>(T a, T b)
   where T : INumber<T>
   where T : IAdditionOperators<T, T, T>
{
   return a + b;
}

注意:在我回答时,此功能只是一个预览。 Microsoft 将在 .NET 6 的最终版本中保留这一点,因为他们仍然希望允许突破机会。要使用该功能,必须在项目配置中启用预览功能:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <EnablePreviewFeatures>true</EnablePreviewFeatures>
    <LangVersion>preview</LangVersion>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="System.Runtime.Experimental" Version="6.0.0-preview.7.21377.19" />
  </ItemGroup>

</Project>

【讨论】:

    猜你喜欢
    • 2011-05-01
    • 2014-08-16
    • 1970-01-01
    • 2021-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多