简体   繁体   English

Type 的 C# 通用约束是可转换的

[英]C# generic constraint for Type to be castable

Is there a way with C# generics to limit a type T to be castable from another type?有没有办法使用 C# 泛型来限制类型T可以从另一种类型转换?

Example :示例
Lets say I am saving information in the registry as a string , and when I restore the information I would like to have a function that looks something like that:假设我将注册表中的信息保存为string ,当我恢复信息时,我想要一个看起来像这样的函数:

static T GetObjectFromRegistry<T>(string regPath) where T castable from string 
{
    string regValue = //Getting the registry value...
    T objectValue = (T)regValue;
    return objectValue ;
}

There is no such type of constraints in .NET. .NET 中没有这种类型的约束。 There is only six types of constraints available (see Constraints on Type Parameters ):只有六种类型的约束可用(请参阅类型参数的约束):

  • where T: struct type argument must be a value type where T: struct类型参数必须是值类型
  • where T: class type argument must be a reference type where T: class类型参数必须是引用类型
  • where T: new() type argument must have a public parameterless constructor where T: new()类型参数必须有一个公共的无参数构造函数
  • where T: <base class name> type argument must be or derive from the specified base class where T: <base class name>类型参数必须是或派生自指定的基类
  • where T: <interface name> type argument must be or implement the specified interface where T: <interface name>类型参数必须是或实现指定的接口
  • where T: U type argument supplied for T must be or derive from the argument supplied for U where T: U为 T 提供的where T: U类型参数必须是或派生自为 U 提供的参数

If you want to cast string to your type, you can do casting to object first.如果你想将字符串转换为你的类型,你可以先转换为对象。 But you can't put constraint on type parameter to make sure this casting can occur:但是您不能对类型参数施加约束以确保可以发生此转换:

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

Another option - create interface:另一种选择 - 创建接口:

public interface IInitializable
{
    void InitFrom(string s);
}

And put it as constraint:并将其作为约束:

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

Types are determined during compilation.类型是在编译期间确定的。 You can't change the types during runtime.您不能在运行时更改类型。 It is possible to cast object to its base or child class可以将对象强制转换为其基类或子类

Ref -参考 -

Difference between object a = new Dog() vs Dog a = new Dog() 对象 a = new Dog() 与 Dog a = new Dog() 之间的区别

Constraints spell out like "the type of T must either be of type U or inherit type U", so the constraint you are looking for isn't doable.约束拼写为“T 的类型必须是 U 类型或继承 U 类型”,因此您正在寻找的约束是不可行的。

everything is "castable" to String anyway, through .ToString() (YMMV)无论如何,一切都可以通过.ToString() (YMMV)“投射”到String

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM