避免必须在泛型函数中指定 T 类型

Avoid having to specify T type in a generic function

我有这个通用扩展函数,它可以将具有特定父类型的对象转换为子类型(在此处找到代码:Unable to Cast from Parent Class to Child Class):

public static U ParentToChild<T, U>(this T parent) {
    if(!typeof(U).IsSubclassOf(typeof(T)))
        throw new Exception(typeof(U).Name + " isn't a subclass of " + typeof(T).Name);
    var serializedParent = JsonConvert.SerializeObject(parent);
    return JsonConvert.DeserializeObject<U>(serializedParent);
}

因此,当我调用此函数时,我需要同时指定父项和子项 class 类型,例如:

Child child = parent.ParentToChild<Parent, Child>();

有什么方法可以避免 'Parent' 精度吗?

我想写这个:

Child child = parent.ParentToChild<Child>();

您可以将参数类型设置为 object 并删除类型参数 T

public static U ParentToChild<U>(this object parent) {
    // note how I used "parent.GetType()" instead of `typeof(T)`
    if (!typeof(U).IsSubclassOf(parent.GetType()))
        throw new Exception(typeof(U).Name + " isn't a subclass of " + parent.GetType().Name);
    var serializedParent = JsonConvert.SerializeObject(parent);
    return JsonConvert.DeserializeObject<U>(serializedParent);
}

顺便说一下,您的方法并没有充分利用泛型类型参数 T。您可以将其用作 U 的约束,避免运行时检查:

public static U ParentToChild<T, U>(this T parent) where U : T {
    //                                            ^^^^^^^^^^^^^
    var serializedParent = JsonConvert.SerializeObject(parent);
    return JsonConvert.DeserializeObject<U>(serializedParent);
}

因此,如果您使用 object 作为参数,您将失去此编译时类型检查。