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中没有这种类型的约束。仅有六种类型的约束可用(请参阅“类型参数上的约束”):
where T: struct
类型实参必须是值类型where T: class
类型实参必须是引用类型where T: new()
类型实参必须具有公共的无参数构造函数where T: <base class name>
类型参数必须是指定基类或从指定基类派生where T: <interface name>
类型参数必须是或实现指定的接口where T: U
为T提供的类型实参必须是或从为U提供的实参派生如果要将字符串强制转换为您的类型,则可以先强制转换为对象。但是您不能对类型参数施加约束以确保可以进行这种强制转换:
static T GetObjectFromRegistry<T>(string regPath)
{
string regValue = //Getting the regisstry value...
T objectValue = (T)(object)regValue;
return objectValue ;
}
另一个选项-创建界面:
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 ;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句