在其他类型.net中强制转换动态对象

时间:2013-07-11 06:00:42

标签: .net casting

.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对象,但我无法访问动态添加的字段。 感谢

1 个答案:

答案 0 :(得分:0)

当编译器为表达式organization.Name生成代码时,它会将变量organization的类型检测为dynamic。然后它决定推迟绑定&#39;执行时间的过程,因为它不知道变量organization背后的对象将具有NameModifiedOn属性。只要动态对象没有相应的成员,就会在执行期间调用方法TryGetMemberTrySetMember。在此示例中,TryGetMemberTrySetMember不会为属性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?)