简体   繁体   中英

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#:

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.

There is plenty of answers on SO about various workaround, but non of them explains why language designers not implemented such feature. From amount of questions on SO it looks like it would be useful in read world applications.

Why this feature was not implemented in C#, are there any chances that it will be added in next version of the language?

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.

There is speculation that the CLR may be modified in order for a future C# version (7.0?) to support this feature.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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