Sca*_*aux 4 c# syntax keyword new-operator method-declaration
一位同事给了我一些我必须在.NET应用程序中使用的C#类.
有一个我从未见过的拼写错误,我在互联网上找不到任何解释......
这是代码:
public void GoTo<TView>() where TView : Form, new()
{
var view = Activator.CreateInstance<TView>();
//si on vient de creer une startup view alors on affiche l'ancienne
//la reference a la nouvelle sera detruite en sortant de la fonction GoTo
if (view is StartupForm)
{
ShowView(_StartupForm);
}
else ShowView(view);
}
Run Code Online (Sandbox Code Playgroud)
new()在方法声明的最后是什么关键字?
请参阅MSDN:
新约束指定泛型类声明中的任何类型参数都必须具有公共无参数构造函数.要使用新约束,类型不能是抽象的.
所以当你说:
void myMethod<T>(T item) where T : class, new();
Run Code Online (Sandbox Code Playgroud)
那么这意味着你在泛型参数T上设置一个约束.所以T应该是一个引用类型,不能是一个值类型(int,float,double等).T也应该有一个无公共参数的默认构造函数.