简体   繁体   English

为什么C#中的通用参数没有构造函数与参数的约束?

[英]Why there is no constructor-with-parameters constrain on generic parameters in C#?

As we all know, we cannot write code like this in current version of C#: 众所周知,我们无法在当前版本的C#中编写如下代码:

public class A {
    public static void Method<T> () where T : new(string, string) {
        var x = new T("foo", "bar");
    }
}

but we may use new() constrain to enforce that T has public parameter-less constructor, and then we are able to create new instances of T using new T() expression. 但是我们可以使用new()约束来强制T具有无参数的公共构造函数,然后我们可以使用new T()表达式创建T新实例。

There is plenty of answers on SO about various workaround, but non of them explains why language designers not implemented such feature. 关于各种变通办法,SO上有很多答案,但是没有一个可以解释为什么语言设计人员没有实现这种功能。 From amount of questions on SO it looks like it would be useful in read world applications. 从大量的SO问题看来,它在阅读世界的应用程序中似乎很有用。

Why this feature was not implemented in C#, are there any chances that it will be added in next version of the language? 为什么没有在C#中实现此功能,是否有可能在该语言的下一版本中添加它?

According to this feature request link on github , the reason is that the CLR doesn't provide the information that C# needs to implement it. 根据github上的功能请求链接 ,原因是CLR没有提供C#实现它所需的信息。

There is speculation that the CLR may be modified in order for a future C# version (7.0?) to support this feature. 有人猜测可能会修改CLR,以便将来的C#版本(7.0?)支持此功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM