【问题标题】:Updating an object property in C#, passing the property as a parameter?在 C# 中更新对象属性,将属性作为参数传递?
【发布时间】:2019-12-09 21:33:46
【问题描述】:

我正在更新一个 loooong... 对象的属性列表。我想知道是否有办法将 propertyName 作为参数传递。

因此,在我检查了对象中是否存在属性之后(我知道该怎么做) - 我可以只写 UpdateObject(ObjectName, propertyName, NewValue)。

如您所知,我处于 ​​C# 学习曲线的底部。我已经在 SO 中查找了关于这个问题的“类似问题”,但没有成功,至少我能理解......

如果你能指出我正确的方向,那就太好了。

无论如何,我必须感谢这个优秀的 SO' 贡献者社区,因为多年来我从你的帖子中得到了很多很多的提示和答案。

实际上,我听从了您的建议并同意了:

Type type = target.GetType();
PropertyInfo prop = type.GetProperty("propertyName");
prop.SetValue (target, propertyValue, null);
// where target is the object that will have its property set.

谢谢大家

【问题讨论】:

  • 如果你能指出正确的方向 System.Reflection 获取对象类型,找到给定的属性,设置它
  • 你的意思是用 'UpdateObject(obj, 'X', Y)' 替换 'obj.X = Y' 吗?
  • 看看这个关于如何使用System.Reflectionstackoverflow.com/a/619778/8882410的答案
  • 听起来你想使用 AutoMapper 之类的东西。
  • 有办法做到这一点。但是因为你说你正在学习 C#,所以最好问问你为什么要这样做。这是学习过程的一个正常部分,我们想要违背语言的运作方式,这会导致使用反射。但是,如果我们了解您为什么要这样做 - 您要解决什么问题 - 那么也许有一个不需要这样做的解决方案。

标签: c# object parameters updating


【解决方案1】:

你可以使用反射来做到这一点:

class Prop
{
   public string Name {get;set;}
   public object Value {get;set;}
}

public void AssignProperties(object obj, List<Prop> properties)
{
   var objPropSetters = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).ToDictionary(p => p.Name, p => p.GetSetMethod()); // create a dictionary where the key is the property name and the value is the property's setter method
   properties.ForEach(p => objPropSetters[p.Name].Invoke(obj, p.Value)); // Invoke the setter
}

您可以通过缓存每个类型的 objPropSetters 以供重复使用来提高性能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-25
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-23
    • 1970-01-01
    相关资源
    最近更新 更多