通用方法将新 T 添加到 T 列表
Generic method add new T to list of T
我正在尝试将一个通用列表传递给一个函数,该函数将向列表中添加一个新项目。我有以下精简示例:
private void SetBayNumb<T>(ObservedList<T> bayList) where T : IBaySpec, new()
{
var bay = new T();
bayList.Add(bay);
}
调用它的方法有这个错误:
The type T' must have a public parameterless constructor in order to
use it as parameter
T' in the generic type or method
我想做的事情可行吗?我觉得它一定是因为编译器不应该关心它是什么类型的列表 - 它只需要调用 public,无参数构造函数并将新实例添加到传入的现有列表中。
我猜问题是接口不保证它的实现者会有一个 public 构造函数,但即使我给它一个具体的 class 我也会得到这个错误:
The type T' must be convertible to
BayClass' in order to use it
as parameter `T' in the generic type or method
非常感谢任何指点。
投诉不是关于名单,而是关于 T
。如果你有一个 ObservedList<MyClass>
并将它传递给 SetBayNumb()
,MyClass
必须实现 IBaySpec
并且它必须有一个无参数构造函数:public MyClass() { ... }
。为什么?因为那是 where T : IBaySpec, new()
所说的。如果删除 where
子句,错误将消失,但您将无法再说 new T()
.
我觉得你的调用代码看起来像
void Method<T>(ObservedList<T> bayList)
{
SetBayNumb<T>(bayList);
}
问题来自 Method
中的 T
没有限制,因此编译器无法匹配 SetBayNumb
.
的参数
请注意,通用类型名称只是名称 - 您可以选择任何您喜欢的名称,它可以帮助推理错误。使用不同命名的通用参数重写相同的方法,例如:
void Method<TArg>(ObservedList<TArg> bayList)
{
SetBayNumb<TArg>(bayList);
}
给出更好的错误:
The type 'TArg' must have a public parameterless constructor in order to use it as parameter 'T' in the generic type or method
请注意错误涉及 2 种不同的类型(当两者调用相同时很难看出 "T")。
修复:
- 对外部泛型方法指定相同的限制 (
Method<TArg>(ObservedList<TArg> bayList) where TArg : ... new()
)
- 在通用 class 级别而不是个别方法上指定
T
- 传递满足这两个要求的具体 class(class 列表中的项目应实现接口并具有无参数构造函数)。
我正在尝试将一个通用列表传递给一个函数,该函数将向列表中添加一个新项目。我有以下精简示例:
private void SetBayNumb<T>(ObservedList<T> bayList) where T : IBaySpec, new()
{
var bay = new T();
bayList.Add(bay);
}
调用它的方法有这个错误:
The type
T' must have a public parameterless constructor in order to use it as parameter
T' in the generic type or method
我想做的事情可行吗?我觉得它一定是因为编译器不应该关心它是什么类型的列表 - 它只需要调用 public,无参数构造函数并将新实例添加到传入的现有列表中。
我猜问题是接口不保证它的实现者会有一个 public 构造函数,但即使我给它一个具体的 class 我也会得到这个错误:
The type
T' must be convertible to
BayClass' in order to use it as parameter `T' in the generic type or method
非常感谢任何指点。
投诉不是关于名单,而是关于 T
。如果你有一个 ObservedList<MyClass>
并将它传递给 SetBayNumb()
,MyClass
必须实现 IBaySpec
并且它必须有一个无参数构造函数:public MyClass() { ... }
。为什么?因为那是 where T : IBaySpec, new()
所说的。如果删除 where
子句,错误将消失,但您将无法再说 new T()
.
我觉得你的调用代码看起来像
void Method<T>(ObservedList<T> bayList)
{
SetBayNumb<T>(bayList);
}
问题来自 Method
中的 T
没有限制,因此编译器无法匹配 SetBayNumb
.
请注意,通用类型名称只是名称 - 您可以选择任何您喜欢的名称,它可以帮助推理错误。使用不同命名的通用参数重写相同的方法,例如:
void Method<TArg>(ObservedList<TArg> bayList)
{
SetBayNumb<TArg>(bayList);
}
给出更好的错误:
The type 'TArg' must have a public parameterless constructor in order to use it as parameter 'T' in the generic type or method
请注意错误涉及 2 种不同的类型(当两者调用相同时很难看出 "T")。
修复:
- 对外部泛型方法指定相同的限制 (
Method<TArg>(ObservedList<TArg> bayList) where TArg : ... new()
) - 在通用 class 级别而不是个别方法上指定
T
- 传递满足这两个要求的具体 class(class 列表中的项目应实现接口并具有无参数构造函数)。