方法声明末尾的 new() 关键字

new() keyword at the end of method declaration

一位同事刚给了我一些 C# 类,我必须在 .NET 应用程序中使用它。
有个错字我没见过,网上也找不到解释...

代码如下:

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

}

方法声明末尾的 new() 关键字有什么用?

type parameter constraint。从字面上看,它意味着 TView 必须有一个 public 无参数构造函数。

参见MSDN

The new constraint specifies that any type argument in a generic class declaration must have a public parameterless constructor. To use the new constraint, the type cannot be abstract.

所以当你说:

void myMethod<T>(T item) where T : class, new();

那么这意味着你对泛型参数 T 进行了约束。所以 T 应该是引用类型,不能是值类型(int, float, double etc) .另外 T 应该有一个 public parameter-less 默认构造函数。

这是一个类型参数约束,具体为 constuctor-constraint,详见 C# 语言规范第 10.1.5 节。

If the where clause for a type parameter includes a constructor constraint (which has the form new() ), it is possible to use the new operator to create instances of the type (§7.6.10.1). Any type argument used for a type parameter with a constructor constraint must have a public parameterless constructor (this constructor implicitly exists for any value type) or be a type parameter having the value type constraint or constructor constraint (see §10.1.5 for details).

这只是一种保证传入的类型可以用无参数构造函数构造的方法。