简体   繁体   English

当您知道C#属性值的类名(不是属性名)时,设置它

[英]Setting C# property value when you know its class name (not property name)

I have a class as follows: 我的课如下:

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

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

where all the properties are guaranteed to have classes as their types and will be unique. 其中所有属性都保证具有类作为其类型,并且将是唯一的。 I would like to use reflection to set the value for the property given a particular type. 我想使用反射来设置给定特定类型的属性的值。 So for Set1ReturnDto : 因此对于Set1ReturnDto

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

and then for Set2ReturnDto 然后对于Set2ReturnDto

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

EDIT: 编辑:

This is part of the needed knowledge to implement requirements for Generic approach to dealing with multiple result sets from EF stored procedure 这是实施通用方法来处理EF存储过程的多个结果集所需知识的一部分

This will do it: 这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM