为什么不支持C#隐含泛型类型的类的构造函数?不支持、函数、类型

2023-09-02 10:30:16 作者:King

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();

这是需要匿名类型,你不知道是什么类型的参数会(在智能感知它显示为),因为它是由编译器添加

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#只是缺乏一套规则,使这一切成为可能。我认为,开发商从来没有见过的neccesity包括这个。事实上,以下code将是非常接近你的主张和解决问题。所有的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);

由于这code的实际工作中,我们已经表明,这个问题不是一语义,而只是缺少扶持的企业之一。我想我要收回我的previous张贴。 ; - )

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. ;-)