简体   繁体   English

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

[英]Generic method with unspecified type possible?

I do need a solution for loading lists of objects - lookups where only one property is referenced from the current object as in this example. 我确实需要一个加载对象列表的解决方案 - 查找其中只有一个属性从当前对象引用,如本例所示。

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

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

For the lookup I need a List to be loaded from the database, to know from where to load the information I use an Attribute 对于查找,我需要从数据库加载List,以了解从何处加载我使用Attribute的信息

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

After reading out the PropertyInfo for the WorkingObject.City Property I know the type of the lookup object, and from which class with which method to load it. 在读出了WorkingObject.City属性的PropertyInfo之后,我知道了查找对象的类型,以及从哪个类加载它的方法。 Now I need the bridge to get a List with that three parameters to work with. 现在我需要桥接器来获取具有这三个参数的List。

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

Since I need the typed List<> for using properties of the LookupObjects on the UI, how can I become a useable list in Code? 由于我需要使用类型化的List <>来在UI上使用LookupObjects的属性,我如何成为Code中的可用列表?

My ideal Outcome would be, if I could just type: 我理想的结果是,如果我可以输入:

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

where the parameters are read from the Attribute. 从Attribute中读取参数的位置。

In order to produce a List<T> type, and thus instance, at runtime, where T comes from a Type object (ie. not known at compile-time), you would do this: 为了生成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);

This will produce, at runtime, the correct list type and store it in the list variable. 这将在运行时生成正确的列表类型并将其存储在list变量中。

Note that there is no way you can get the compiler to infer the variable type, so this: 请注意,您无法让编译器推断变量类型,因此:

var list = Loader.Load(...)

will still not produce a List<T> type , it will have to use a non-generic, known-at-compile-time type to store the list, like IList , but the object you store in it can be a generic one, produced the way I describe above. 仍然不会生成List<T> 类型 ,它必须使用非泛型的,编译时已知的类型来存储列表,如IList ,但是您存储在其中的对象可以是通用的,产生了我上面描述的方式。

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

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