我应该如何在最后一行实现int(z * 2)的乘法.

public static TResult Test<TResult>() where TResult : INumber<TResult>
{
    TResult x = TResult.AdditiveIdentity;
    TResult y = TResult.MultiplicativeIdentity;
    TResult z = x * y;
    TResult z2 = z * 2; // <--- this gives the CS0019 error "The operator * cannot be applied to operands of type 'TResult' and 'int'
    return z2;
}

-建议的解决方案是添加一个接口,但它打破了这一点: IMultiplyOperators<TResult, int, TResult>

public static void Tester()
{
    Test<decimal>(); // CS0315 Tye type decimal cannot be used as type parameter TResult..... there is no boxing conversion 
}

现在,我将自己注入该函数并使用:

public static TResult Test<TResult>(Func<TResult, int, TResult> mul) where TResult : INumber<TResult>
{
    TResult x = TResult.AdditiveIdentity;
    TResult y = TResult.MultiplicativeIdentity;
    TResult z = x * y;
    TResult z2 = mul(z, 2); 
    return z2;
}

推荐答案

我建议将converting2TResult相乘:

   TResult z2 = z * TResult.CreateChecked(2);

在这里,我们从整数值2创建TResult个实例,而对于溢出和类似的可能错误,则创建checking2(如果2不能转换为TResult,则会引发异常).

Code:

public static TResult Test<TResult>() where TResult : INumber<TResult>
{
    TResult x = TResult.AdditiveIdentity;
    TResult y = TResult.MultiplicativeIdentity;
    TResult z = x * y;
    TResult z2 = z * TResult.CreateChecked(2);
    return z2;
}

Demo:

Console.WriteLine(Test<decimal>());

Output:

0

Fiddle

Csharp相关问答推荐

WPF文本框点击鼠标 Select 内容

WeakHandle .NET核心与.NET框架

从LED面板中提取文本

try 在C#中启动Tunnelbear.Exec

将多个enum值传递给MAUI中的转换器参数的XML语法是什么?

如何从顶部提取发票号作为单词发票后的第一个匹配

使用变量子根名称在C#中重新初始化SON文件

C#XmlSerializer-输出控制新行的多个XML片段

Quartz调度程序不调用作业(job)类

如何使用NumberFormatInfo

如何使用XmlSerializer序列化带有CDATA节的XML文件?

C#中Java算法的类似功能

Google OAuth令牌交换在.Net中不起作用

无法使用[FromForm]发送带有图像和JSON的多部分请求

在扩展方法中,IEnumerable<;T>;不会转换为IEumerable<;T&>

实体框架-IsRequired()与OnDelete()

工厂类是如何在.NET 8中注册的?

数据库操作预计影响1行,但实际影响0行; after _dbContext.SaveChanges();

无效的Zip文件-Zip存档

反序列化我以前使用System.Text.Json序列化的文件时出现异常