c# - 为了在构造函数中实例化类型参数,类声明必须满足什么?
问题描述
我发现哪个给定的类定义将允许我创建这样的构造函数的问题。经过测试,只有“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
{
}
我的问题与标题相同:类声明必须满足什么才能在构造函数中实例化类型参数?
解决方案
这不会编译,因为约束 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()
.
推荐阅读
- git - 不明白为什么 git merge -s ours 会忽略以前的提交
- javascript - 将每个其他数组元素的第一个字母大写
- flutter - 值更改后小部件宽度不更新
- android - 如何调整每个平台的小部件大小?
- javascript - React - 如何将两个值而不是一个传递给钩子
- flutter - 增加从顶部到网格视图第一行的内边距
- python - 从 sympy 获得不定积分
- java - 在应用程序中的时间过去后显示文本
- for-loop - 在 Go 中循环切片以创建地图
- java - 在 RESTful Spring Boot 应用程序中,如何对嵌套对象属性进行 url 查询?