使用反射其中实际类型为通用v2

问题描述

这是我在here之前问过的问题的稍作修改

实际位置如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace cns01
{
    class Program
    {
        public class datafieldInfo2<T>
        {
            public bool IsSearchValue { get; set; } = false;
            public T Value { get; set; }
        }

        public class SmartRowVertrag
        {
            public datafieldInfo2<int> ID { get; set; }
            public datafieldInfo2<string> VSNR { get; set; }
        }

        static void Main(string[] args)
        {
            SmartRowVertrag tester = new SmartRowVertrag();
            tester.ID = new datafieldInfo2<int>() { Value = 777,IsSearchValue = false };
            tester.VSNR = new datafieldInfo2<string>() { Value = "234234234",IsSearchValue = true };

            var g = RetData3(tester);
        }

        public static object RetData3(object fsr)
        {
            object retVal = new object();
            var props = fsr.GetType().GetProperties();
            foreach (var prop in props)
            {
                PropertyInfo propInfo = prop.GetType().GetProperty("IsSearchValue"); // <-- here I get null
                propInfo = prop.PropertyType.GetProperty("IsSearchValue"); // here I get a propertyInfo,but...
                dynamic property = propInfo.GetValue(fsr,null); // ...<-- here fires error
                var result = property.IsSearchValue;
                if (result == true)
                {
                    // doThis
                }
            }
            return retVal;
        }
    }
}

我确实需要获取存储在IsSearchValue中的布尔值才能完成任务。

谢谢。

我非常感谢有帮助的答案。

解决方法

fsrSmartRowVertrag。您正在尝试从中获取IsSearchValue-但它不存在。

相反,您需要调用GetValue两次-在prop上一次,传入fsr(因此等效于使用fsr.ID或{{1} }),然后在dsr.VSNR上一次传递第一个调用的结果。

接下来,您使用propInfo的目的是根据dynamic的结果获取IsSearchValue-您正在尝试有效地评估propInfo.GetValue()

以下是该部分的更正代码:

something.IsSearchValue.IsSearchValue

尽管您有public static object RetData3(object fsr) { object retVal = new object(); var props = fsr.GetType().GetProperties(); foreach (var prop in props) { PropertyInfo propInfo = prop.PropertyType.GetProperty("IsSearchValue"); if (propInfo != null) { object fieldInfo = prop.GetValue(fsr); object isSearchValue = propInfo.GetValue(fieldInfo); if (isSearchValue.Equals(true)) { Console.WriteLine($"{prop.Name} has a searchable field"); } } } return retVal; } 实现的非通用接口或基类,也可以避免两次使用反射。例如:

DataFieldInfo2<T>

然后您可以使反射代码更清晰:

public interface IDataFieldInfo
{
    bool IsSearchValue { get; }
}

public class DataFieldInfo2<T> : IDataFieldInfo
{
    ...
}