英文:
How to generate constant values with generic math
问题
以下是翻译的代码部分:
我有以下通用数学函数:
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 = Five * Two;
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);
}
这种方法感觉有点像一个小技巧,是否有更好的方法?
英文:
I have the following generic math function:
private static T Fade<T>(T t)
where T : IFloatingPoint<T>
{
return t * t * t * (t * (t * 6 - 15) + 10);
}
This doesn't compile however, since 6
, 15
and 10
are not of type T
.
The best solution I could come up with was to define a static class like this:
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 = Five * Two;
public static readonly T Fifteen = Five * Three;
}
And then the function becomes this:
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);
}
This feels a bit like a hack though, is there a nicer way to do this?
答案1
得分: 9
You can use one of the INumberBase<T>.CreateX
methods, for example INumberBase<TSelf>.CreateChecked<TOther>(TOther)
to convert the number literals to the generic number type:
private static T Fade<T>(T t)
where T : IFloatingPoint<T>
{
return t * t * t *
(t * (t * T.CreateChecked(6) - T.CreateChecked(15)) + T.CreateChecked(10));
}
英文:
You can use one of the INumberBase<T>.CreateX
methods, for example INumberBase<TSelf>.CreateChecked<TOther>(TOther)
to convert the number literals to the generic number type:
private static T Fade<T>(T t)
where T : IFloatingPoint<T>
{
return t * t * t *
(t * (t * T.CreateChecked(6) - T.CreateChecked(15)) + T.CreateChecked(10));
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论