繁体   English   中英

可能的未指定类型的通用方法?

[英]Generic method with unspecified type possible?

我确实需要一个加载对象列表的解决方案 - 查找其中只有一个属性从当前对象引用,如本例所示。

class LookupObjectAddress
{
 [...]
 public string City
 { get; set; }
 [...]
}

class WorkingObject
{
 // references the property from LookupObjectAddress
 public string City
 { get; set; }
}

对于查找,我需要从数据库加载List,以了解从何处加载我使用Attribute的信息

class WorkingObject
{
 // references the property from LookupObjectAddress
 [Lookup(Type=typeof(LookupObjectAddress), staticloaderclass="LookupObjLoader", staticloaderMethod="LookupObjLoadMethod")]
 public string City
 { get; set; }
}

在读出了WorkingObject.City属性的PropertyInfo之后,我知道了查找对象的类型,以及从哪个类加载它的方法。 现在我需要桥接器来获取具有这三个参数的List。

Type loaderClass = Type.GetType(classname);
MethodInfo loaderMethod = loaderClass.GetMethod(loadmethod);
object objList = loaderMethod.Invoke(null, new object[] {});

由于我需要使用类型化的List <>来在UI上使用LookupObjects的属性,我如何成为Code中的可用列表?

我理想的结果是,如果我可以输入:

var list = Loader.Load(type, "LookupObjLoader", "LookupObjLoadMethod");

从Attribute中读取参数的位置。

为了生成List<T>类型,从而在运行时生成T,其中T来自Type对象(即在编译时不知道),您可以这样做:

Type genericListType = typeof(List<>); // yes, this really is legal syntax
Type elementType = ...
Type specificListType = genericListType.MakeGenericType(elementType);
// specificListType now corresponds to List<T> where T is the same type
// as elementType
IList list = (IList)Activator.CreateInstance(specificListType);

这将在运行时生成正确的列表类型并将其存储在list变量中。

请注意,您无法让编译器推断变量类型,因此:

var list = Loader.Load(...)

仍然不会生成List<T> 类型 ,它必须使用非泛型的,编译时已知的类型来存储列表,如IList ,但是您存储在其中的对象可以是通用的,产生了我上面描述的方式。

暂无
暂无

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

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