10

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 ;
}
4

3 回答 3

7

.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 ;
}
于 2013-07-24T06:50:09.117 回答
0

约束拼写为“T 的类型必须是 U 类型或继承 U 类型”,因此您正在寻找的约束是不可行的。

String无论如何,通过.ToString()(YMMV) ,一切都是“可铸造的”

于 2013-07-24T07:05:21.190 回答
0

类型是在编译期间确定的。您不能在运行时更改类型。可以将对象转换为其基类或子类

参考 -

对象 a = new Dog() 与 Dog a = new Dog() 之间的区别

于 2013-07-24T06:49:06.707 回答