Why is reflection not finding property
I have a class:
class Person
{
public string Name { get { return "Antonio"; } }
}
and the code:
IEnumerable<object> uncknownObject;
uncknownObject = new ObservableCollection<Person>( );
var observCol = uncknownObject.GetType( );
var x = ( ( dynamic )observCol ).GenericTypeArguments[ 0 ];
var y = observCol.GetProperty( "GenericTypeArguments" );
var instance = ( Person )Activator.CreateInstance( x );
Console.WriteLine( instance.Name ); // Print Antonio!!!
why y == null
?
Pay attention to the picture:
the debugger shows that the GenericTypeArguments property should exist, and the code shows opossite. It can be proven that the debugger is right and this property exists because whereas x is not null. If this property exists, then why y
is it zero !!! ???
Edit
Thanks to Ani, I now have:
IEnumerable<object> uncknownObject;
uncknownObject = new ObservableCollection<Person>();
var observCol = uncknownObject.GetType();
var genTypeArgsProperty = typeof(Type).GetProperty("UnderlyingSystemType");
var genTypeArgsValue = (genTypeArgsProperty.GetValue(observCol, null));
var f = genTypeArgsValue.GetType().GetMethod("GetGenericArguments");
IEnumerable<object> result = (IEnumerable<object>)f.Invoke(genTypeArgsValue, null);
var x = result.FirstOrDefault();
var instance = Activator.CreateInstance( (Type)x );
In case you are curious as to what I need this functionality for, click here
source to share
I really don't understand what you are trying to accomplish with all this meta-meta-reflection, but you seem to have misunderstood what it does Type.GetProperty
. It retrieves the metadata for a property by the actual type represented by the instance System.Type
(in this case ObservableCollection<Person>
). It does not receive metadata for a self-declared property System.Type
, unless of course you name it on the System.Type
represent System.Type
.
In your case, y
it is null as it ObservableCollection<Person>
does not have a property named "GenericTypeArguments".
Try this instead:
var genTypeArgsProperty = typeof(Type).GetProperty("GenericTypeArguments");
var genTypeArgsValue = (Type[]) (genTypeArgsProperty.GetValue(observCol, null));
var onlyTypeArgValue = genTypeArgsValue.Single();
source to share
This code works with grid 4:
IEnumerable<object> uncknownObject;
uncknownObject = new ObservableCollection<Person>();
var observCol = uncknownObject.GetType();
var x = ((dynamic) observCol).UnderlyingSystemType.GetGenericArguments()[0];
var y = observCol.GetGenericArguments();
var instance = (Person)Activator.CreateInstance(x);
Console.WriteLine(instance.Name); // Print Antonio!!!
source to share