C#不要求你指定一個泛型類型參數,如果編譯器可以推斷它,比如:爲什麼C#不支持類構造函數中的隱含泛型類型?
List<int> myInts = new List<int> {0,1,1,
2,3,5,8,13,21,34,55,89,144,233,377,
610,987,1597,2584,4181,6765};
//this statement is clunky
List<string> myStrings = myInts.
Select<int,string>(i => i.ToString()).
ToList<string>();
//the type is inferred from the lambda expression
//the compiler knows that it's taking an int and
//returning a string
List<string> myStrings = myInts.
Select(i => i.ToString()).
ToList();
這是需要匿名類型,你不知道類型參數會是什麼(在intellisense中顯示爲'a
),因爲它是由編譯器添加的。
類級別類型參數不要讓你這樣做:
//sample generic class
public class GenericDemo<T>
{
public GenericDemo (T value)
{
GenericTypedProperty = value;
}
public T GenericTypedProperty {get; set;}
}
//why can't I do:
int anIntValue = 4181;
var item = new GenericDemo(anIntValue); //type inference fails
//however I can create a wrapper like this:
public static GenericDemo<T> Create<T> (T value)
{
return new GenericDemo<T> (value);
}
//then this works - type inference on the method compiles
var item = Create(anIntValue);
爲什麼不C#支持這一類級別泛型類型推斷?
爲什麼這個問題有一個投票結果反對它作爲[爲什麼不能C#構造函數推斷類型?](http://stackoverflow.com/questions/3570167)當這個問題是兩年更近?當然這是重複的? – Keith 2013-07-04 09:06:54
我認爲其他問題更簡潔,它有一個更好的答案。 – Sam 2013-10-08 04:13:01