首页 > 解决方案 > 为了在构造函数中实例化类型参数,类声明必须满足什么?

问题描述

我发现哪个给定的类定义将允许我创建这样的构造函数的问题。经过测试,只有“Test1”类没有抛出任何错误,但我想知道它必须继承什么,或者必须分配“T”才能实例化“T”

    class Test<T> : TestClass, ITest
    {
        public Test()
        {
            var t = new T();

        }
    }
    class Test1<T> where T : TestClass, new()
    {
        public Test1()
        {
            var t = new T();

        }
    }
    class Test2<T> where T : object
    {
        public Test2()
        {
            var t = new T();

        }
    }
    class TestClass
    {

    }
    interface ITest
    {

    }

我的问题与标题相同:类声明必须满足什么才能在构造函数中实例化类型参数?

标签: c#

解决方案


这不会编译,因为约束 toTestClass并不能确保存在无参数构造函数,即使TestClass确实有无参数构造函数:

class Test<T> : TestClass, ITest
{
    public Test()
    {
        var t = new T();
    }
}

这是因为可以使用派生类型来定义带参数的构造函数:

class DerivedTestClass : TestClass
{
    public DerivedTestClass(SomeType something) { }
}

var test = new Test<DerivedTestClass>(); // How can Test construct a DerivedTestClass?

出于这个原因,new()总是需要约束才能调用new T().


推荐阅读