Type为可强制转换的C#泛型约束

Avi*_*ner 8 c# generics

有没有办法使用C#泛型来限制类型T可以从另一种类型转换?

示例:
假设我将信息保存在注册表中string,当我恢复信息时,我希望有一个看起来像这样的函数:

static T GetObjectFromRegistry<T>(string regPath) where T castable from string 
{
    string regValue = //Getting the regisstry value...
    T objectValue = (T)regValue;
    return objectValue ;
}
Run Code Online (Sandbox Code Playgroud)

Ser*_*kiy 5

.NET中没有这种类型的约束.只有六种类型的约束可用(请参阅类型参数的约束):

  • where T: struct type参数必须是值类型
  • where T: class type参数必须是引用类型
  • where T: new() type参数必须具有公共无参数构造函数
  • where T: <base class name> type参数必须是或从指定的基类派生
  • where T: <interface name> type参数必须是或实现指定的接口
  • where T: U 为T提供的类型参数必须是或者从为U提供的参数派生

如果要将字符串强制转换为类型,可以先将对象强制转换为对象.但是你不能在类型参数上加上约束来确保可以发生这种转换:

static T GetObjectFromRegistry<T>(string regPath)
{
    string regValue = //Getting the regisstry value...
    T objectValue = (T)(object)regValue;
    return objectValue ;
}
Run Code Online (Sandbox Code Playgroud)

另一种选择 - 创建界面:

public interface IInitializable
{
    void InitFrom(string s);
}
Run Code Online (Sandbox Code Playgroud)

并把它作为约束:

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 ;
}
Run Code Online (Sandbox Code Playgroud)