2016-11-07 102 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