是否可以使用this.GetType()
作为List
的类型?
我有几个对象继承的以下class
:
public class MainRepository
{
// ??? should be the type of this
public List<???> GetAll()
{
return new List<???>();
}
}
我知道它可以像这样的通用方法完成:
public List<T> GetAll<T>()
{
return new List<T>();
}
但我想知道是否可以在没有明确定义调用方法中的类型的情况下完成。
答案 0 :(得分:2)
这只能通过反射实现,因为对象的真实类型仅在运行时才知道。因此,您必须设计方法以返回所有列表的公共基类,这是.NET中的对象,并动态地在方法中创建列表。
public object GetAll()
{
return System.Activator.CreateInstance(typeof(List<>).MakeGenericType(this.GetType()));
}
但是,我不明白你为什么要那样做。
答案 1 :(得分:1)
我相信你能做到这一点,如果这对你来说是可行的选择吗?:
public class MainRepository<T>
{
public List<T> GetAll()
{
return new List<T>();
}
}
如果我没有弄错的话,那应该允许你调用方法而不在方法调用中指定类型(尽管你显然必须为类指定它)。
我假设你想要这样做,以便有一些通用的通用存储库,可以是子类,或类似的东西?然后你可以做一些像(只是一个粗略的想法):
public class BaseRepo {
}
public class MainRepository<T> : BaseRepo where T : BaseRepo{
public List<T> GetAll(){
return new List<T>();
}
}