【发布时间】:2023-02-07 02:49:17
【问题描述】:
我有以下通用数学函数:
private static T Fade<T>(T t)
where T : IFloatingPoint<T>
{
return t * t * t * (t * (t * 6 - 15) + 10);
}
但是,这不会编译,因为 6、15 和 10 不是 T 类型。
我能想到的最好的解决方案是定义一个静态类,如下所示:
private static class GenericValues<T>
where T : IFloatingPoint<T>
{
public static readonly T Two = T.One + T.One;
public static readonly T Three = Two + T.One;
public static readonly T Four = Three + T.One;
public static readonly T Five = Four + T.One;
public static readonly T Six = Five + T.One;
public static readonly T Ten = Two * Three;
public static readonly T Fifteen = Five * Three;
}
然后函数变成这样:
private static T Fade<T>(T t)
where T : IFloatingPoint<T>
{
return t * t * t * (t * (t * GenericValues<T>.Six - GenericValues<T>.Fifteen) + GenericValues<T>.Ten);
}
不过,这感觉有点像 hack,有没有更好的方法来做到这一点?
【问题讨论】:
标签: c# generics .net-7.0 .net-generic-math