.net 4引入了動態對象,您可以在運行時分配屬性。我有動態對象,需要將其轉換爲另一種類型。以下是代碼片段投射其他類型的動態對象.net
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對象,但我已動態添加字段是不是我的訪問。 由於