【问题标题】:Reflection from DTO来自 DTO 的反射
【发布时间】:2011-01-24 18:13:08
【问题描述】:

我有 1 个 dto,statEMailDTO,它有一个字段,其中包含我要查找的字段名称(它们是逗号分隔的。

var emailParams = statEmailDTO.EmailParam.ToString().Split(',');

for (int i = 0; i < emailParams.Length; i++) {
  var fieldName = emailParams[i].ToString();

等等

但是,那么我如何使用反射来获取在不同 DTO siDTO 中找到的 ``fieldName 的实际值。

那么假设fieldName = "SuggestionItemID",那么我将得到siDTO.SuggestionItemID的值。

过去我没有做过很多反思。当然,我阅读了 PropertyInfo,但它只是没有点击。

想法?

【问题讨论】:

    标签: c# reflection dto


    【解决方案1】:

    像这样:

    PropertyInfo property = typeof(SomeType).GetProperty(fieldName);
    object value = property.GetValue(instance, null);
    

    【讨论】:

    • 但是,SomeType 是什么?什么是实例?
    • @Patrick:SomeType 是拥有该属性的类型,instance 是您要获取其值的实例。
    • 如果我执行以下操作... var fieldName = emailParams[i].ToString(); System.Reflection.PropertyInfo 属性 = typeof(SuggestionItemDTO).GetProperty(fieldName);对象 fieldValue = property.GetValue(fieldName, null);然后我得到一个“对象与目标类型不匹配”错误。想法?我的意思是我真的想要 siDTO 的值。“fieldName”
    • 我明白了!冬青废话:System.Reflection.PropertyInfo property = typeof(SuggestionItemDTO).GetProperty(fieldName); object fieldValue = property.GetValue(siDTO, null);
    猜你喜欢
    • 1970-01-01
    • 2017-06-18
    • 2013-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-20
    • 1970-01-01
    • 2019-06-12
    相关资源
    最近更新 更多