2013-07-11 72 views
1

.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對象,但我已動態添加字段是不是我的訪問。 由於

回答

0

當編譯器產生用於表達organization.Name碼檢測可變organization的類型爲dynamic。然後它決定延遲執行時間的「綁定」過程,因爲它不知道變量organization後面的對象將具有NameModifiedOn屬性。只要動態對象沒有相應的成員,方法TryGetMemberTrySetMember就會在執行期間被調用。在這個例子中,TryGetMemberTrySetMember不會被調用屬性名稱,因爲它在eObject上被靜態聲明,但是它們將被調用用於你定義的其他成員訪問。

當你施放該變量在newOrg eObject,編譯器回靜態更新的時候通知,所以可以看到newOrg引用了Name屬性的對象,但沒有ModifiedOn屬性,所以特別newOrg.Name將工作(我不不知道你爲什麼說它不會),但newOrg.ModifiedOn將不會通過編譯器驗證,發出以下錯誤:

 

    '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?) 

相關問題