2011-09-13 28 views
4

我有数百个需要在对象中设置的属性,这是一个等级性质的对象,并且想要这样做的通用方法,这是否可行?其中一个原因是错误检查和记录。使用.NET设置属性值的通用方法

在此示例下面我设置ReferenceModelIdentifier为一个字符串

public override void Execute(MESSAGE message) 
    { 
     message.MISMOReferenceModelIdentifier= "3.0.0.263.12"; 

     Tasks.Add(new AboutVersionsTask(LoanNumber, LoanState)); 
     Tasks.Add(new DealSetsTask(LoanNumber, LoanState)); 

     foreach (var task in Tasks) 
      using (task) 
       task.Execute(message); 

     // Were the tasks successful? 
     Debug.Assert(message.ABOUT_VERSIONS.ABOUT_VERSION.Count > 0, "ABOUT_VERSION"); 
     Debug.Assert(message.DEAL_SETS.DEAL_SET.Count > 0, "DEAL_SET"); 

     Log.Info("Finished Execute"); 
    } 

,并在此示例中,我设定ApplicationReceivedDate类型为MISMODate的另一个目的

public override void Execute(MESSAGE message) 
    { 
     var node = new LOAN_DETAIL(); 

     var con = GetOpenConnection(); 
     string sql; 
     IEnumerable<dynamic> data; 
     dynamic first; 

     if (LoanState == LoanStateEnum.AtClosing) 
     { 
      //(224) ApplicationReceivedDate 
      sql = @" 
       SELECT date ApplicationReceivedDate 
       FROM foo (nolock) 
       WHERE loannum = @loannum"; 

      data = con.Query<dynamic>(sql, new { loannum = new DbString { Value = LoanNumber, IsFixedLength = true, Length = 15, IsAnsi = true } }); 

      first = data.First(); 
      node.ApplicationReceivedDate = new MISMODate { TypedValue = first.ApplicationReceivedDate.ToString("yyyy-MM-dd") }; 
     } 
    } 

我开始了编码是什么沿线

protected void SetValue(Object property, Object value) 
    { 

    } 

和用法wou LD是

SetValue(message.MISMOReferenceModelIdentifier, "3.0.0.263.12"); 

编辑

最后我做什么是这个

protected void SetValue(object theObject, string theProperty, object theValue) 
    { 
     try 
     { 
      var msgInfo = theObject.GetType().GetProperty(theProperty); 
      msgInfo.SetValue(theObject, theValue, null); 

     } 
     catch (Exception e) 
     { 
      Log(e); 
     } 
    } 

和用法是

SetValue(message, "MISMOReferenceModelIdentifier", "3.0.0.263.12"); 

谢谢 斯蒂芬

+0

需要更具体一些 - 代码示例? – BrokenGlass

+1

不确定“对象图”是什么意思,你可以在'System.Reflection'命名空间中使用'PropertyInfo.SetValue()',但这可能不是你所指的。 – StuperUser

+0

根据您的要求提供代码样本。 –

回答

9

可以遍历你的对象图,并设置属性值与反思:

object obj; // your object 

Type t = obj.GetType(); 
foreach (var propInfo in t.GetProperties()) 
{ 
    propInfo.SetValue(obj, value, null); 
} 

如果你能保证你的类属性有干将,你可以重复你的对象图递归:

public static void setValsRecursive(object obj, object value) 
{ 
    Type t = obj.GetType(); 
    foreach (var propInfo in t.GetProperties()) 
    { 
     if (propInfo.PropertyType.IsClass) 
     { 
      object propVal = propInfo.GetValue(obj, null); 
      setValsRecursive(propVal, value); 
     } 
     propInfo.SetValue(obj, value, null); 
    } 
} 

这是一个愚蠢的功能,将每个属性设置为相同的值...

1

您可以使用PropertyInfo以通用方式动态设置值。