使用反射动态地将 属性 转换为其实际类型(其中实际类型是通用的)v3

Cast a property to its actual type dynamically using reflection (where actual type is generic) v3

感谢所有在我之前的 2 个问题中帮助过我的人 and

这是代表代码片段:

using Oracle.ManagedDataAccess.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace cns01
{
    class Program
    {
        public interface IDataFieldInfo
        {
            bool IsSearchValue { get; set; }
        }
        public class DataFieldInfo2<T> : IDataFieldInfo
        {
            public T theValue { get; set; }
            public bool IsSearchValue { get; set; } = false;
        }

        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>() { theValue = 777, IsSearchValue = false };
            tester.VSNR = new DataFieldInfo2<string>() { theValue = "234234234", IsSearchValue = true };

            var g = RetData3(tester);
        }

        public static object RetData3(object fsr)
        {
            List<OracleParameter> oParColl = new List<OracleParameter>();
            var fieldProperties = fsr.GetType().GetProperties()
                .Where(prop => typeof(IDataFieldInfo).IsAssignableFrom(prop.PropertyType));
            foreach (var fieldProperty in fieldProperties)
            {
                var field = (IDataFieldInfo)fieldProperty.GetValue(fsr);
                if (field.IsSearchValue)
                {
                    OracleParameter tmpPar = new OracleParameter()
                    {
                        ParameterName = fieldProperty.Name,
                        Value = fieldProperty.theValue // <-- Designer error: CS1061    'PropertyInfo' does not contain a definition for 'theValue' and no accessible extension method 'theValue' accepting a first argument of type 'PropertyInfo' could be found (are you missing a using directive or an assembly reference?)
                    };
                }
            }
            return null;
        }
    }
}

有什么方法可以独立于类型从 fieldProperty 获取 theValue 吗?由于 OracleParameterValue 属性 是对象,我预计用 theValue.

设置它不会有任何困难

非常感谢任何帮助。

提前致谢。

我注意到你已经尝试了 3 次这个问题,这让我对回答很谨慎

但是,有什么理由可以让您做到以下几点

var propertyValue = fieldProperty.GetValue(fsr);
OracleParameter tmpPar = new OracleParameter()
{
   ParameterName = fieldProperty.Name,
   Value = propertyValue
      .GetType()
      .GetProperty("theValue")
      .GetValue(propertyValue)

};