c# - 什么时候在 C# 中拥有公共(public)无参数构造函数很重要?

标签 c# generics type-constraints

我正在尝试理解 constraints关于 C# 中的泛型类型参数。 where T : new() 约束的目的是什么?为什么您需要坚持类型参数具有公共(public)无参数构造函数?

编辑: 我肯定错过了什么。评分最高的答案说公共(public)无参数构造函数是实例化泛型所必需的。如果是这样,为什么这段代码可以编译和运行?

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //class Foo has no public parameterless constructor
            var test = new genericClass<Foo>(); 
        }
    }

    class genericClass<T> where T : new()
    {
        T test = new T();  //yet no problem instantiating
    }

    class Foo
    {
        //no public parameterless constructor here
    }
}

编辑: 在他的评论中,gabe 提醒我,如果我不定义构造函数,编译器默认会提供一个无参数的构造函数。因此,我示例中的 Foo 类实际上有一个公共(public)无参数构造函数。

最佳答案

如果你想实例化一个新的T

void MyMethod<T>() where T : new()
{
  T foo = new T();
  ...
}

关于c# - 什么时候在 C# 中拥有公共(public)无参数构造函数很重要?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2449817/

相关文章:

C# PrintDocument 打印空白页。为什么?

c# - 为什么 C# 在基本构造函数之前设置私有(private)变量,而 VB.NET 却相反?

斯卡拉,猫。有人可以解释什么是 `F` 以及它从何而来?

Java - 通过构造函数将泛型列表传递给类

Java 将参数约束到公共(public)父类(super class)

c# - 在 C# 中列出 excel 工作簿连接

c# - 使用通用委托(delegate) EventDelegate<T>(T e) 创建一个特殊字典<T, EventDelegate<T>>,其中 T : GameEventBase

java - 通用对象 getter

generics - 将类型约束添加到派生类型F#(此代码不够通用)

haskell - 声明适用于具有特定字段的 Vinyl 记录的约束