简体   繁体   中英

C# DynamicObject: Is there a way to access properties by index?

Is there a way to access the properties of a dynamic object by index?

List<dynamic> list = _dataStagingManager.GetStatusList(consoleSearch);
foreach (var row in list)
{
    Console.WriteLine(row[0]);
    Console.WriteLine(row[1]);
}

In this example, the property name of row[0] is different depending on the results from a stored procedure column alias.

Unfortunately, no. Unlike runtime objects (which have an iterable collection of their members that can easily be reflected/queried against) dynamic objects, by default, have no such collection. They can be implemented in any way that allows their members to be accessed by name. There is no idea of indices with dynamic objects, provided you don't choose to implement them yourself.

If you wanted to, you could override the TryGetIndex method on your dynamic type to provide indexing support.

In general, that's not possible. For example, you could create a dynamic object that has every possible property:

class AnythingGoes : DynamicObject
{
    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        result = binder.Name;
        return true;
    }
}

There is a chance you will be able to get the list of properties. If the dynamic object is actually normal object (one that does not implement IDynamicMetaObjectProvider ), normal reflection will work fine.

If the object actually is dynamic (implements IDynamicMetaObjectProvider ), you could try calling GetDynamicMemberNames() on the DynamicMetaObject returned from GetMetaObject() . But, as the example above shows, this is not guaranteed to work.

I am not familiar with Dapper Dot Net but after a short look at it, it looks as if it is returning anonymous types as dynamic objects. You can look at those as POCOs (plain old CLR objects) meaning that they are classes with individual named properties, probably not implementing any kind of indexer which you would needed to access fields by index.

You could try using Reflection to achieve something similar:

foreach (dynamic propInfo in row.GetType().GetProperties())
{
    Console.WriteLine("{0}: {1}", propInfo.Name, propInfo.GetValue(row, null));
}

I'm not sure you'll get the properties in the same order the stored procedure is returning them, though.

如果row的运行时类型是一个整数索引器,那么你的代码应该没问题。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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