【问题标题】:How to generate constant values with generic math如何使用通用数学生成常量值
【发布时间】: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);
}

但是,这不会编译,因为 61510 不是 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


    【解决方案1】:

    您可以使用INumberBase&lt;T&gt;.CreateX 方法之一,例如INumberBase&lt;TSelf&gt;.CreateChecked&lt;TOther&gt;(TOther)

    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));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-09
      • 1970-01-01
      • 1970-01-01
      • 2019-07-02
      • 2011-01-25
      • 1970-01-01
      • 2020-09-23
      • 1970-01-01
      相关资源
      最近更新 更多