简体   繁体   English

如何将值传递给C#泛型?

[英]How to pass a value to a C# generic?

In C++ templates have the feature that you can pass a value as the argument to the template of a function . 在C ++模板中,您可以将值作为参数传递给函数模板 How can I do the same in C#? 我怎样才能在C#中做同样的事情?

For instance, I want to do something similar to the following: 例如,我想做类似以下的事情:

template <unsigned n> struct Factorial {
     enum { 
        result = n * Factorial<n - 1>::result;
     };
};
template <> struct Factorial<0> {
      enum {
        result = 1;
      };
};

but in C#. 但在C#中。 How can I do this? 我怎样才能做到这一点?

By the way, my actual need for them involves generating classes on demand (with a few static values changed), so the presented code is just an example. 顺便说一下,我对它们的实际需求涉及按需生成类(改变了一些静态值),因此所呈现的代码只是一个例子。

C# generics are not like C++ templates in that way. C#泛型不是那样的C ++模板。 They only work with types and not values. 它们只适用于类型而不是值。

but in C#. 但在C#中。 How can I do this? 我怎样才能做到这一点?

By the way, my actual need for them involves generating classes on demand (with a few static values changed), so the presented code is just an example. 顺便说一下,我对它们的实际需求涉及按需生成类(改变了一些静态值),因此所呈现的代码只是一个例子。

As Daniel explained , this is not possible via generics. 正如丹尼尔解释的那样 ,通过泛型来说这是不可能的。

One potential alternative is to use T4 Templates . 一种可能的替代方案是使用T4模板 Depending on your needs, you could potentially generate your classes based off the templates at compile time, which sounds like it might meet your needs. 根据您的需要,您可以在编译时根据模板生成类,这听起来可能满足您的需求。

You are trying to make the compiler do stuff that your code should do at runtime. 您正在尝试使编译器执行代码应在运行时执行的操作。

Yes, this is possible in C++. 是的,这在C ++中是可行的。 In C#, It is not. 在C#中,它不是。 The equivalent of your code in C# would be: 相当于C#中的代码将是:

public class Factorial
{
    public static ulong Compute(ulong n)
    {
        if (n == 0)
            return 1;
        return n * Factorial.Compute(n - 1);
    }
}

Note that, while static code is already a bad violation of the OOP principle (but sometimes necessary), using value-based templates is even worse. 请注意,虽然静态代码已经严重违反了OOP原则(但有时是必要的),但使用基于值的模板会更糟。 Your types should depend on other types, which is possible using generics. 您的类型应该依赖于其他类型,这可以使用泛型。 They should not depend on concrete values. 他们不应该依赖具体的价值观。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM