有没有办法使用 C# 泛型来限制类型 T
可以从另一个类型转换?
示例:
假设我在注册表中将信息保存为 string
,当我恢复信息时,我希望有一个看起来像这样的函数:
static T GetObjectFromRegistry<T>(string regPath) where T castable from string
{
string regValue = //Getting the registry value...
T objectValue = (T)regValue;
return objectValue ;
}
最佳答案
.NET 中没有此类约束。只有六种类型的约束可用(参见 Constraints on Type Parameters ):
-
where T: struct
类型参数必须是值类型 -
where T: class
类型参数必须是引用类型 -
where T: new()
类型参数必须有一个公共(public)的无参数构造函数 -
where T: <base class name>
类型参数必须是或派生自指定的基类 -
where T: <interface name>
类型参数必须是或实现指定的接口(interface) -
where T: U
为 T 提供的类型参数必须是或派生自为 U 提供的参数
如果你想将字符串转换为你的类型,你可以先转换为对象。但是您不能对类型参数施加约束以确保可以进行此转换:
static T GetObjectFromRegistry<T>(string regPath)
{
string regValue = //Getting the regisstry value...
T objectValue = (T)(object)regValue;
return objectValue ;
}
另一种选择——创建接口(interface):
public interface IInitializable
{
void InitFrom(string s);
}
并将其作为约束:
static T GetObjectFromRegistry<T>(string regPath)
where T: IInitializable, new()
{
string regValue = //Getting the regisstry value...
T objectValue = new T();
objectValue.InitFrom(regValue);
return objectValue ;
}
关于Type 可转换的 C# 泛型约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17826995/