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();
이것은 당신이 형식 매개 변수가 (어떻게 될지 모르는 익명 형식에 필요 인텔리 센스에서는 컴파일러에 의해 추가 되었기 때문에 '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) 그 질문이 2 년 더 최근입니까? 확실히 그게 복제품이야? – Keith
나는 다른 질문이 더 간결하다고 생각하며, 더 나은 대답을 가지고있다. – Sam
@Sam - 예, 에릭 리 퍼트의 대답은 권위가 있지만 어느 쪽의 질문도 닫지 않아야한다고 생각합니다. – Keith