.net 4 引入了动态对象,您可以在其中在运行时分配属性。我有动态对象,需要将其转换为另一种类型。以下是代码片段
public class eObject : DynamicObject
{
Dictionary<string, object> m_dictFields = new Dictionary<string, object>();
private string m_strName;
public string Name
{
get { return m_strName; }
set { m_strName = value; }
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (m_dictFields.ContainsKey(binder.Name))
{
result = m_dictFields[binder.Name];
return true;
}
else
{
return base.TryGetMember(binder, out result);
}
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
if (!m_dictFields.ContainsKey(binder.Name))
m_dictFields.Add(binder.Name, value);
else
m_dictFields[binder.Name] = value;
return true;
}
}
// now I am assigning properties to my dynamic object as
static void Main(string[] args)
{
dynamic organization = new eObject();
organization.Name = "Test Org Name";
organization.ModifiedOn = DateTime.Now;
organization.CreatedOn = DateTime.Now;
organization.ModifiedBy = "Test Modified by";
oganization.CreatedBy = "Test User";
// this is what i have done
eObject newOrg = organization as eObject;
Console.WriteLine("Org Name: " +organization.Name); // working
Console.WriteLine("Org Name: " +newOrg.Name); // not working
}
我正在获取 newOrg 对象,但我无法访问我动态添加的字段。谢谢