2016-11-07 100 views
0

在C#中:是否可以使用泛型参数类的类型作为方法的返回类型或定义成员?类似于C++模板中的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; 
} 
+0

我投票结束这个问题作为题外话,因为它不是代码转换工具! – mybirthname

+0

是的,这是可能的,你可以学习C#泛型,你可以在任何地方使用它们https://msdn.microsoft.com/en-us/library/512aeb7t.aspx –

+5

@mybirthname他没有要求代码转换工具。他问C#中是否有并行功能,并且包含一个C++示例来展示他所指的概念。 –

回答

0

你作为这样的例子没有一个干净的翻译到C#,因为它使有关的一般类型的可用的方法的假设。 C#允许您将泛型类型限制为特定类型或接口的后代或实现者,但这是尽可能多的。如果该方法在编译时无法解析为类型,则不会编译。

+0

有没有“不洁净”的方法来解决它? – monotomy

+0

我不认为有静态方法。如果我没有记错,在C#中,静态方法是不可继承的。 –

+0

静态并不重要 - 我只使用static来使C++示例尽可能简短和简单(没有对象实例化)。 – monotomy