[英]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.