我应该如何在最后一行实现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;
}