【问题标题】:Setting C# property value when you know its class name (not property name)当你知道它的类名(不是属性名)时设置 C# 属性值
【发布时间】:2015-07-15 14:19:37
【问题描述】:

我有一堂课如下:

  public class DummyReturnDto
  {
      public Set1ReturnDto Foo { get; set; }
      public Set2ReturnDto Bar { get; set; }

      public DummyReturnDto()
      {
          Set1 = new Set1ReturnDto();
          Set2 = new Set2ReturnDto();
      }
  }

所有属性都保证有类作为它们的类型并且是唯一的。我想使用反射来设置给定特定类型的属性的值。所以对于Set1ReturnDto

var propertyInfo = obj.GetType().GetProperty(Set1ReturnDto, ??????);
propertyInfo.SetValue(obj, value, null);

然后对于 Set2ReturnDto

var propertyInfo = obj.GetType().GetProperty(Set2ReturnDto, ??????);
propertyInfo.SetValue(obj, value, null);

编辑:

这是实现Generic approach to dealing with multiple result sets from EF stored procedure 要求所需知识的一部分

【问题讨论】:

  • 您确定每种类型在您的班级中只出现一次DummyReturnDto
  • @TheEdge 你到底为什么想要这个?
  • 为什么要为此使用反射?您不能只保留一个从类型到实例的内部字典,并让 getter 和 setter 委托给该字典吗?你想达到什么目的?反射很少是解决方案。
  • @Vincent 最终我将使用这个将类列表传递给我的方法。类(不是对象实例)的排序将是经过深思熟虑的,因为我需要从数据库返回的内容中提取多个结果集并将它们映射到每个数据集。请参阅stackoverflow.com/questions/31399498/… 以及我在原始帖子中发布的链接。
  • 对我来说,使用单个方法 SetProperty(Type t, object o) 创建一个接口并在您的帮助程序类中使用它而不是泛型类型 T 似乎更容易(这消除了反射的需要)。 DummyReturnDto 应该通过从Typeobject 的字典来实现该接口。所有的吸气剂都会做类似Set1ReturnDto Foo { get { return (Set1ReturnDto)_dict[typeof(Set1ReturnDto)]; } } 的事情。这样就解决了这个问题吧?

标签: c#


【解决方案1】:

这样就可以了:

var propertyInfo = typeof(DummyReturnDto).GetProperties()
                       .Single(p => p.PropertyType == typeof(Set1ReturnDto));

【讨论】:

  • 这假定每种类型在类中只出现一次。如果这不是所需的行为(从 tgread 中不清楚),您可以相应地更改 .Single-part。
  • @HimBromBeere 你说得对,我的解决方案基于are guaranteed to have classes as their types and will be unique :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-13
  • 1970-01-01
  • 2020-09-04
  • 1970-01-01
  • 2021-07-23
相关资源
最近更新 更多