Type 可转换的 C# 泛型约束

标签 c# generics

有没有办法使用 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/

相关文章:

c# - 使用泛型的类型安全 : Check T to Interface<T>

java - 泛型友好的类型处理程序映射

Java:构建器、继承、泛型 Redux

c# - 如何在右键单击 WPF DataGrid 时访问 DataGridCell

c# - 有条件地加入 LINQ

c# - XML 批量更改类型十六进制

Java 泛型 - 这两个方法声明等效吗?

c# - 当 C# 在同一个包含类中时,为什么以及如何允许访问类本身外部的私有(private)变量?

c# - 序列化 .NET WCF 服务类型的问题 : Service WSDL defines empty types in XSD

java - 在运行时创建具有反射和泛型的类的数组