gpt4 book ai didi

c# - 具有未指定类型的通用方法可能吗?

转载 作者:太空狗 更新时间:2023-10-30 01:11:53 25 4
gpt4 key购买 nike

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

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

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

对于查找,我需要从数据库中加载一个列表,以便知道从何处加载我使用属性的信息

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

读出 WorkingObject.City 属性的 PropertyInfo 后,我知道了查找对象的类型,以及从哪个类使用哪种方法加载它。现在我需要桥来获得一个包含这三个参数的列表。

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

由于我需要类型化的 List<> 才能在 UI 上使用 LookupObjects 的属性,我怎样才能成为代码中可用的列表?

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

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

从属性中读取参数的位置。

最佳答案

为了产生List<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> type,它必须使用非通用的、编译时已知的类型来存储列表,例如 IList ,但您存储在其中的对象可以是通用对象,按照我上面描述的方式生成。

关于c# - 具有未指定类型的通用方法可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1593308/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com