2017-01-17 46 views
-1

初始化對象考慮到我具有如以下結構的對象: -動態上運行時根據需要

RootObject 
    Personal 
     Forename 
     Surname 
     Middlename 
    Telephone 
     LandLine 
     Mobile 

當我供給

<Ruleset> 
    <Field>Personal.Forename</Field> 
    <FieldValue>World</Field> 
</Ruleset> 
<Ruleset> 
    <Field>Personal.Surname</Field> 
    <FieldValue>Hello</Field> 
</Ruleset> 

當我的供應商規則集

我當電話沒有初始化時,根據需求初始化RootObject中的'Personal'對象(反之亦然)。

請指教我如何能夠實現這一點,而無需在整個RootObject子代(和孩子的孩子)中編寫初始化/構造函數代碼,因爲我正在尋找一個動態解決方案,可以使用而不必返工初始化一段代碼。謝謝

+0

投票的人請提供解釋。 這不是一個「家庭作業」的東西,因爲我已經嘗試了幾種方法,包括將其轉換爲對象並執行.GetType()然後初始化它。 只要在Root對象中有新類時,我就必須更新整個GetType()開關。 –

回答

0

不知道我是否正確理解你,但如果你想要,你可以使用反射。

如果RuleSet看起來是這樣的:

public class RulleSet 
    { 
     public string ObjectName { get; set; } 
     public string PropertyName { get; set; } 
     public object value { get; set; } 
    } 

你可以在你的類創建方法:

public void Initialize(RulleSet initRule) 
    { 
     var initializableObject = this.GetType().GetProperty(initRule.ObjectName).GetValue(this,null); 
     //If object not initialized, we need to create it 
     if (initializableObject == null) 
     { 
      initializableObject = 
       Activator.CreateInstance(this.GetType().GetProperty(initRule.ObjectName).PropertyType); 
      PropertyInfo propertyInfo = this.GetType().GetProperty(initRule.ObjectName); 
      propertyInfo.SetValue(this, Convert.ChangeType(initializableObject, propertyInfo.PropertyType), null); 
     } 
     //If we have object, we created it or it already axist doesn't matter we set property 
     if (initializableObject != null) 
     { 
      var initializableProperty = 
       initializableObject.GetType().GetProperty(initRule.PropertyName).GetValue(initializableObject, null); 
      initializableProperty = Activator.CreateInstance(initializableObject.GetType().GetProperty(initRule.PropertyName).PropertyType); 
      PropertyInfo propertyInfo = initializableObject.GetType().GetProperty(initRule.PropertyName); 
      propertyInfo.SetValue(initializableObject, Convert.ChangeType(initializableProperty, propertyInfo.PropertyType), null); 
     } 
    } 

沒有測試:)所以可能會有一些錯誤,如果你想您可以將其設置爲靜態,只需在代表初始化對象的方法中添加其他參數,並用此參數替換this即可。 PS。 ofc由於使用反射,它可能會更慢,沒有編碼初始化。