C# 使用.NET设置属性值的通用方法
我有数百个属性需要在一个对象中设置,这个对象本质上是分层的,并且想要一种通用的方法来设置,这可行吗?驱动原因之一是错误检查和日志记录 在下面的示例中,我将ReferenceModelIdentifier设置为字符串C# 使用.NET设置属性值的通用方法,c#,C#,我有数百个属性需要在一个对象中设置,这个对象本质上是分层的,并且想要一种通用的方法来设置,这可行吗?驱动原因之一是错误检查和日志记录 在下面的示例中,我将ReferenceModelIdentifier设置为字符串 public override void Execute(MESSAGE message) { message.MISMOReferenceModelIdentifier= "3.0.0.263.12"; Tasks.Add(new
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") };
}
}
而且用法是
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");
谢谢,,
Stephen您可以使用以通用方式动态设置值。您可以迭代对象图并使用反射设置属性值:
object obj; // your object
Type t = obj.GetType();
foreach (var propInfo in t.GetProperties())
{
propInfo.SetValue(obj, value, null);
}
如果可以确保类属性具有getter,则可以递归迭代对象图:
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);
}
}
这是一个将每个属性设置为相同值的哑函数…需要更具体一点-代码示例?不确定“对象图”的含义,您可以在
系统.Reflection
命名空间中使用PropertyInfo.SetValue()
,但这可能不是您所指的。根据您的请求提供代码示例。
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);
}
}