gpt4 book ai didi

c# - 对对象使用 C# 动态方法

转载 作者:太空狗 更新时间:2023-10-29 21:55:30 25 4
gpt4 key购买 nike

我有一个方法应该从列表中返回 ID。通常我会为此任务使用反射(我不能使用通用方法,因为这些类通常是不共享接口(interface)或基类的 POCOS,我无法修改它们)。但是,我想到了新的 dynamic 关键字并想尝试一下。

但是我的问题是 dataSource[index] 返回一个对象。那么在运行时,确保对象本身在我自己的类中并且具有 id 属性。但我想因为该方法返回一个对象,所以我在运行时访问 current.id

时得到一个 RumtineBinderException
public List<int> GetItemIds()
{

var result = new List<int>();
var dataSource = GetDataSource(); // returns an List<Object>

for (int i = 0; i <= dataSource.Count - 1; i++)
{
dynamic current = dataSource[i];
int id = current.Id; // throws RuntimeBinderException: Object has no definition for id
}

return result;
}

有没有办法实现我想要的,或者我是否必须返回反射来获取 id 属性?

更新:

current.GetType() returns object
current.GetType().GetProperties() returns a TargetInvocationException

我的 Pocos 存在于我的主项目 (VB.net) 中,但此方法位于类库中,也许这就是原因。然而:

object current = dataSource[i];
PropertyInfo prop = current.GetType().GetProperty("id", BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
if (prop != null)
{
int id = (int)prop.GetValue(current, null);
}

有效。

最佳答案

我相信您可能需要将“GetDataSource()”的返回类型定义为“List<dynamic>”。

当然,如评论中所述,对象必须定义属性“id”。

关于c# - 对对象使用 C# 动态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6695773/

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