[英]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 的prop1
和prop2
上調用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.