the problem is that we cannot GetValue of a field (non generic) that only resides in base class that has generic type. please see the code snippet below. calling
f.GetValue(a)
will throw the exception with message: Late bound operations cannot be performed on fields with types for which Type.ContainsGenericParameters is true.
class Program
{
static void Main(string[] args)
{
Type abstractGenericType = typeof (ClassB<>);
FieldInfo[] fieldInfos =
abstractGenericType.GetFields(BindingFlags.Public | BindingFlags.Instance);
ClassA a = new ClassA("hello");
foreach(FieldInfo f in fieldInfos)
{
f.GetValue(a);// throws InvalidOperationhException
}
}
}
internal class ClassB<T>
{
public string str;
public ClassB(string s)
{
str = s;
}
}
internal class ClassA : ClassB<String>
{
public ClassA(string value) : base(value)
{}
}
Our design requires that we obtain FieldInfo first before we have any instances of actual objects. so we cannot use
Type typeA = abstractGenericType.MakeGenericType(typeof(string));
FieldInfo[] fieldInfos = typeA.GetFields();
Thank you
a.GetType()
to get the concrete generic type, no point in going through the incomplete type. – Analyzer