为什么 C# 不支持类构造函数中隐含的泛型类型?
C# 不要求您指定泛型类型参数,如果编译器可以推断它,例如:
C# doesn't require you to specify a generic type parameter if the compiler can infer it, for instance:
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
),因为它是由编译器添加的.
This is needed for anonymous types where you don't know what the type parameter would be (in intellisense it shows up as 'a
) because it's added by the compiler.
类级别的类型参数不允许您这样做:
Class-level type parameters don't let you do this:
//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# 不支持此类级别的泛型类型推断?
Why doesn't C# support this class level generic type inference?
其实你的问题还不错.过去几年我一直在研究泛型编程语言,虽然我从未真正开发它(可能永远不会),但我对泛型类型推断进行了很多思考,我的首要任务之一是一直允许在不必指定泛型类型的情况下构造类.
Actually, your question isn't bad. I've been toying with a generic programming language for last few years and although I've never come around to actually develop it (and probably never will), I've thought a lot about generic type inference and one of my top priorities has always been to allow the construction of classes without having to specify the generic type.
C# 只是缺乏使这成为可能的规则集.我认为开发人员从来没有看到包含这个的必要性.实际上,以下代码将非常接近您的命题并解决问题.所有 C# 需要的是附加的语法支持.
C# simply lacks the set of rules to make this possible. I think the developers never saw the neccesity to include this. Actually, the following code would be very near to your proposition and solve the problem. All C# needs is an added syntax support.
class Foo<T> {
public Foo(T x) { … }
}
// Notice: non-generic class overload. Possible in C#!
class Foo {
public static Foo<T> ctor<T>(T x) { return new Foo<T>(x); }
}
var x = Foo.ctor(42);
由于这段代码确实有效,我们已经证明问题不在于语义,而在于缺乏支持.我想我必须收回我以前的帖子.;-)
Since this code actually works, we've shown that the problem is not one of semantics but simply one of lacking support. I guess I have to take back my previous posting. ;-)