【发布时间】:2018-07-06 09:59:07
【问题描述】:
我有这个通用扩展函数,它将具有特定父类型的对象转换为子类型(在此处找到代码: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);
}
所以当我调用这个函数时,我需要同时指定父类和子类类型:
Child child = parent.ParentToChild<Parent, Child>();
有什么办法可以避免'父'精度?
我想写这个:
Child child = parent.ParentToChild<Child>();
【问题讨论】:
-
不,没有办法做到这一点。
标签: c# function casting parent-child generic-function