知道其类名(而不是属性名)时设置C#属性值

时间:2015-07-14 05:47:38

标签: c#

我有一个课程如下:

  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

要求所需知识的一部分

1 个答案:

答案 0 :(得分:4)

This will do it:

var propertyInfo = typeof(DummyReturnDto).GetProperties()
                       .Single(p => p.PropertyType == typeof(Set1ReturnDto));
相关问题