gpt4 book ai didi

c# - 为什么 C# 不支持类构造函数上的隐式泛型类型?

转载 作者:IT王子 更新时间:2023-10-29 03:51:18 25 4
gpt4 key购买 nike

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# 只是缺少使这成为可能的规则集。我认为开发人员从未认为有必要将其包括在内。实际上,以下代码将非常接近您的命题并解决问题。 C# 所需要的只是一个添加的语法支持。

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

由于这段代码确实有效,我们已经表明问题不是语义问题,而只是缺乏支持问题。我想我必须收回我之前的帖子。 ;-)

关于c# - 为什么 C# 不支持类构造函数上的隐式泛型类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45604/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com