Reputation: 874
ADDED: What I want to do. I have something, for example, DataReader, from which I want to create IEnumerable of objects with members as in DataReader. So, in design and compile time I don't know how many properties will be in my dynamic object (depends on how many columns contains in DataReader) and it names. AND I need to create such dynamic anonymous object with properties with right names and values, to get this properties in future by reflection...
I thought about DynamicObject and that's what I've done:
I have DynamicObject class:
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
namespace makarov.ReportManager.InternalLogic
{
public class DataReaderParcer : DynamicObject
{
private readonly Dictionary<string, object> m_properties;
public DataReaderParcer()
{
m_properties = new Dictionary<string, object>();
}
public bool SetMember(string name, object value)
{
if (m_properties.ContainsKey(name))
m_properties.Remove(name);
m_properties.Add(name, value);
return true;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
return SetMember(binder.Name, value);
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = null;
if (m_properties.ContainsKey(binder.Name))
result = m_properties[binder.Name];
return m_properties.ContainsKey(binder.Name);
}
public override IEnumerable<string> GetDynamicMemberNames()
{
return from p in m_properties select p.Key;
}
}
}
And here is the usage:
dynamic dd = new DataReaderParcer();
dd.MyMember= 3;
dd.YourMember= "hello";
How to retrieve PropertyInfo[] of this object using Reflection in another method? Something like this dd.GetType().GetProperties()
doesn't work correctly because DataReaderParcer don't have any properties.
Upvotes: 2
Views: 4481
Reputation: 14672
You are derriving from DynamicObject therefore you can call GetDynamicMemberNames to get an enumeration your members.
http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.getdynamicmembernames.aspx
dynamic dd = new DataReaderParcer();
IEnumerable<string> members = dd.GetDynamicMemberNames();
Upvotes: 3