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

问题描述

感谢所有在我之前的两个问题www.example.org/starthere中为我提供帮助的人。

这是代表代码片段:

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;
        }
    }
}

有什么方法可以独立于类型从theValue获取fieldProperty吗?由于OracleParameter的{​​{1}}属性是对象,因此使用Value设置它不会有任何困难。

任何帮助将不胜感激。

事先谢谢。

解决方法

我注意到您对此问题进行了3次尝试,这使我对回答的问题保持警惕

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

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

};