2012-08-02 105 views
2

如果我有一個約束爲類型'int'的泛型方法,那麼當然我應該能夠將一個整型轉換爲泛型T型。例如...C#泛型約束的泛型方法拒絕從整型轉換爲泛型

public T ExampleMethod<T>(int unchanged) where T : int 
    { 
     return (T)unchanged; 
    } 

...編譯器抱怨無法將類型「詮釋」到「T」但我有一個約束指示目標是爲整數。所以肯定它應該工作?

更新:

的實際情況是,我想返回一個枚舉值一個輔助方法。所以,我的理想輔助方法,會更喜歡這個....

public T GetAttributeAsEnum<T>(XmlReader reader, string name) where T : enum 
{ 
    string s = reader.GetAttribute(name); 
    int i = int.Parse(s); 
    return (T)i; 
} 

...並使用它像這樣...

StateEnum x = GetAttributeAsEnum<StateEnum>(xmlReader, "State"); 
CategoryEnum y = GetAttributeAsEnum<CategoryEnum>(xmlReader, "Category"); 
OtherEnum z = GetAttributeAsEnum<OtherEnum>(xmlReader, "Other"); 

...但你無法通過枚舉約束。

+0

爲什麼不指定參數類型爲'T' ? – gilly3 2012-08-02 04:06:06

+0

我的實際情況比較複雜。我想要一個幫助器方法,從文件中讀取一個字符串,該字符串實際上是一個數字。然後將該數字轉換爲正確的目標枚舉類型。所以... – 2012-08-02 04:09:31

+0

這不會編譯。錯誤:'int'不是有效的約束。用作約束的類型必須是接口,非密封類或類型參數。 – 2012-08-02 04:09:49

回答

7

只有類或接口可以被指定爲約束。」(三)ReSharper的

INT(Int32)已只是一個結構。你可以限制這個T是結構。但是你不能使用任何結構作爲約束。

可能的約束,你可以在這裏找到整個列表 - http://msdn.microsoft.com/en-us/library/d5x73970.aspx

UPD

和枚舉約束看到這個問題 - Is there a workaround for generic type constraint of "special class" Enum in C# 3.0?

+0

A * struct *也可以用作約束。以下編譯:'public class Generic where T:struct {}'。然後,您可以將該類實例化爲「Generic gen = new Generic ();'。 – 2012-08-02 04:15:42

+0

@EricJ。你不明白。我們可以將T約束爲「一個結構」,但我們不能使用任何結構作爲約束。 – 2012-08-02 04:24:19

+0

我明白你來自哪裏。然而,現在的答案是誤導。除了* struct *之外,您還可以指定* new *作爲約束。這兩者都不是「階級或界面」。 – 2012-08-02 04:35:10

4

int(以及所有其他數值類型和枚舉)不能用作通用約束。

進一步的細節和選項見

Generic C# Code and the Plus Operator

對於安德斯·海爾斯伯格,C#的創建者的討論,關於泛型和類型約束看到

http://www.artima.com/intv/generics.html

一個可以放置結構的類型約束是這樣的:

public class Generic<T> where T : struct { } 

Generic<int> gen = new Generic<int>(); 
+1

** Downvoter **:這個答案有什麼問題?分享,這樣我們都可以學習。 – 2012-08-02 04:20:17

2

你確定它的編譯?

在這裏,它提供了以下錯誤:

error CS0701: 'int' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter.