对对象使用C#动态方法

Jür*_*ock 6 .net c# reflection dynamic-language-runtime

我有一个方法应该从List返回ID.通常我会使用反射来完成这个任务(我不能使用泛型方法,因为类通常是不共享接口或基类的POCOS,我不能修改它们).但是,我想到了新的dynamic关键字,并想尝试这个.

但是我的问题是dataSource [index]返回一个对象.在运行时,确保对象本身是我自己的类并具有id属性.但我想因为该方法返回一个对象,我在访问时会在运行时获得RumtineBinderExceptioncurrent.id

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;
}
Run Code Online (Sandbox Code Playgroud)

有没有办法实现我想要或做的事情我必须回到反思来获取id属性?

更新:

current.GetType() returns object
current.GetType().GetProperties() returns a TargetInvocationException
Run Code Online (Sandbox Code Playgroud)

我的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);
}
Run Code Online (Sandbox Code Playgroud)

作品.

小智 1

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

当然,正如注释中所述,对象必须定义属性“id”。