查看this问题 我开始考虑如何在 C# 中处理构造函数要求。
假设我有:
T SomeMethod<T>(string s) : where T : MyInterface
{
return new T(s);
}
我想对 T
设置要求,它可以由字符串构造,但据我所知,构造函数定义不允许作为接口(interface)的一部分。有解决这个问题的标准方法吗?
最佳答案
向您的界面添加一个初始化方法或属性,
public interface MyInterface
{
void Init(string s);
string S { get; set; }
}
T SomeMethod<T>(string s) : where T : MyInterface, new()
{
var t = new T();
t.Init(s);
var t = new T
{
S = s
};
return t;
}
因为您不能为构造函数约束指定参数
关于c# - 泛型参数的构造函数要求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6129496/