繁体   English   中英

C# 反射获取FieldInfo背后的实例

[英]C# Reflection get the instance behind FieldInfo

我遇到了反射问题,我似乎找不到解决方案。

我有以下简单的界面:

    public interface IDataProperty<T> 
{
   public T Value { get; set; } 
   public int BytesCount();
   public byte[] Serialize();
}

实现上述接口的结构:

    public struct IntProperty : IDataPropery<int> 
{
    private int _value; 
    public int Value { get => _value; set => _value = value; }

    public int BytesCount()
    {
        return 4;
    }

    public byte[] Serialize()
    {
        return BitConverter.GetBytes(_value);
    }
    public IntDataProperty(int value) { _value = value; }
}

和一个简单的 class 来保存值:

public class ValuesContainer  
{
   public IntProperty prop1;
   public IntProperty prop2;
}

我正在尝试在我的处理器 class 的prop1prop2上调用Serialize()方法,但到目前为止没有运气......:

public class Processor  
{
   public void ProccesData<T>(out T result) where T : ValuesContainer, new() 
    {
      result = new T();
        List<FieldInfo> dataFields = new List<FieldInfo>();
        result.GetType().GetFields().ToList().ForEach(field => { 
        if(field.FieldType.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IDataProperty<>)))
            {
                dataFields.Add(field);
            }
              });
         MethodInfo serializeMI = typeof(IDataProperty<>).GetMethod("Serialize");
         foreach(FieldInfo field in dataFields)
        {
            Console.WriteLine(field.Name);
            serializeMI.Invoke(field,null);
        }

    }
}

此时运行代码会出现以下错误:

'Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.'

我知道我需要以某种方式获取field变量后面的实例,但不知道该怎么做。 有谁知道用其他方法做我正在尝试实现的事情的好方法,或者只有反射是通往 go 的方式,如果是后者 - 我有什么解决方案?

在此先感谢大家。

在评论中提供@JeroenMostert 的大力帮助后,我已经能够从根本上解决问题。 只要 Jeroen 没有提供被接受为正确的答案,我就会展示他的解决方案,所以这个问题被标记为已回答。 不过,这里的好处是@JeroenMostert

    internal class Program
  {
     static void Main(string[] args)
        {
            ValuesContainer container = new ValuesContainer();
            Processor processor = new Processor();
            processor.ProccesData(out container);
        }
     }
    public interface IDataProperty<T>
    {
        public void Serialize();
    }
    public struct IntProperty : IDataProperty<int>
    {
        private int _value;
        public int Value { get => _value; set => _value = value; }

        public int BytesCount()
        {
            return 4;
        }

        public void Serialize()
        {
            Console.WriteLine("I have been invoked !" + this.GetHashCode());
        }
    }
    public class ValuesContainer
    {
        public IntProperty prop1;
        public IntProperty prop2;
    }
    public class Processor
    {
        public void ProccesData<T>(out T result) where T : ValuesContainer, new()
        {
            result = new T();
            List<FieldInfo> dataFields = new List<FieldInfo>();
            result.GetType().GetFields().ToList().ForEach(field => {
                if (field.FieldType.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IDataProperty<>)))
                {
                    dataFields.Add(field);
                }
            });         
            foreach (FieldInfo field in dataFields)
            {
                Console.WriteLine("Invoking 'Serialize' method on fieldName :" + field.Name);
              field.GetValue(result).GetType().GetMethod("Serialize").Invoke(field.GetValue(result), null);          
            }
        }
    }

暂无
暂无

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

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