.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对象,但我无法访问动态添加的字段。 感谢
答案 0 :(得分:0)
当编译器为表达式organization.Name
生成代码时,它会将变量organization
的类型检测为dynamic
。然后它决定推迟绑定&#39;执行时间的过程,因为它不知道变量organization
背后的对象将具有Name
或ModifiedOn
属性。只要动态对象没有相应的成员,就会在执行期间调用方法TryGetMember
和TrySetMember
。在此示例中,TryGetMember
和TrySetMember
不会为属性Name调用,因为它在eObject
上静态声明,但它们将被调用以用于您定义的其余成员访问。
在newOrg中将变量强制转换为eObject
时,编译器将返回静态分析,因此可以看到newOrg引用具有Name
属性但没有ModifiedOn
属性的对象,因此特别是newOrg.Name
会起作用(我不知道你为什么说它没有),但是newOrg.ModifiedOn
没有通过编译器验证,发出以下错误:< / p>
'eObject' does not contain a definition for 'ModifiedBy' and no extension method 'ModifiedBy' accepting a first argument of type 'eObject' could be found (are you missing a using directive or an assembly reference?)