gpt4 book ai didi

c# - 使用 .NET 设置属性值的通用方法

转载 作者:太空狗 更新时间:2023-10-29 20:55:21 25 4
gpt4 key购买 nike

我有数百个属性需要在一个对象中设置,这个对象本质上是分层的,我想要一个通用的方法来这样做,这可行吗?驱动原因之一是错误检查和日志记录。

在下面的示例中,我将 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)
{

}

用法是

    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");

谢谢,斯蒂芬

最佳答案

您可以遍历对象图并使用反射设置属性值:

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);
}
}

这是一个将每个属性设置为相同值的愚蠢函数......

关于c# - 使用 .NET 设置属性值的通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7405048/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com