C# 对类型层次结构中的所有派生类型调用泛型方法
假设我们有以下类型层次结构:C# 对类型层次结构中的所有派生类型调用泛型方法,c#,C#,假设我们有以下类型层次结构: public abstract class Base {} public class A : Base {} public class B : Base {} 我需要对Base中的所有派生类型执行相同的操作。这就是我想到的 public IList<T> DoWork<T>(string entityPath) where T : Base { // get 'json' using 'entityPath' return
public abstract class Base {}
public class A : Base {}
public class B : Base {}
我需要对Base
中的所有派生类型执行相同的操作。这就是我想到的
public IList<T> DoWork<T>(string entityPath) where T : Base {
// get 'json' using 'entityPath'
return JsonConvert.DeserializeObject<List<T>>(json);
}
这显然不起作用
如果这种方法完全有缺陷,我很想知道替代方法。如果在编译时不知道类型,就不能使用泛型,但幸运的是,
jsonvert.DeserialiseObject
有一个重载,它接受一个字符串和一个类型
因此,您可以添加非泛型的DoWork
重载:
public object DoWork(string entityPath, Type type) {
// get 'json' using 'entityPath'
var listType = typeof(List<>).MakeGenericType(type);
return JsonConvert.DeserializeObject(json, listType);
}
在实际代码中,不会忽略返回值。第一句话是否意味着即使是基类型也不能以多态方式使用(即,
DoWork(path)
其中base实际上是a
的实例)?在语句DoWork(path)
中,base
只是base
。它不可能是A
Base
是一种类型,而一种类型不能是另一种类型的实例,所以我不太清楚您的意思@这是一个愚蠢的问题,我需要学习更多关于泛型的知识,谢谢!
public object DoWork(string entityPath, Type type) {
// get 'json' using 'entityPath'
var listType = typeof(List<>).MakeGenericType(type);
return JsonConvert.DeserializeObject(json, listType);
}
foreach(var e in entitties) {
DoWork(e.Key, e.Value); // why are you ignoring the return value?
}