c#泛型中的类型演绎类似于c++模板

Type deduction in C# generics like in C++ templates?

本文关键字:类似于 c++ 模板 演绎 类型 泛型      更新时间:2023-10-16

在c#中:是否可以使用泛型参数类的类型作为方法的返回类型或定义成员?

c++的例子:

class AgrumentClass
{
    typedef int type;
public:
    static type GetSomething() { return 0; }
};
template< class T >
class GenericClass
{
    typedef typename T::type type;
public:
    static type GetSomething() { return T::GetSomething(); }
};
int main()
{
    int value = GenericClass<AgrumentClass>::GetSomething();
    return value;
}

这样的例子没有一个清晰的c#翻译,因为它对泛型类型上可用的方法做了一个假设。c#允许您将泛型类型限制为特定类型或接口的后代或实现者,但这是您所能做到的。如果该方法不能在编译时解析为该类型,则它将无法编译。