反思为什么不找物业 [英] Why reflection does not find property

查看:120
本文介绍了反思为什么不找物业的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类:

    class Person 
    {
        public string Name { get { return "Antonio"; } }
    }

和代码:

        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!!!

为什么 y == null

请注意图片:

调试器显示属性 GenericTypeArguments 应存在,代码显示opossite中。可以证明调试器是正确的,该属性存在,因为那么x如何不是null。如果该属性存在,那么为什么 y 等于null !!! ???

the debugger shows that the property GenericTypeArguments should exist and the code shows the opossite. It can be proven that the debugger is right and that property exist because then how come x is not null. If that property exists then why y is equal to null!!!???

感谢Ani我现在有:

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

推荐答案

我真的不明白你想用这个元荟萃反射完成什么,但你似乎误解了 Type.GetProperty 。它获取由 System.Type 实例表示的实际类型上的属性的元数据(在这种情况下, ObservableCollection< Person> )。它不会获得在 System.Type 本身声明的属性的元数据,除非当然你调用它 System.Type 表示 System.Type 本身。

I don't really understand what you're trying to accomplish with all this meta-meta-reflection, but you seem to have misunderstood what Type.GetProperty does. It gets meta-data for a property on the actual type represented by the System.Type instance (in this case, ObservableCollection<Person>). It does not get meta-data for a property declared on System.Type itself, unless of course you call it on a System.Type representing System.Type itself.

在您的情况下, y 为null,因为 ObservableCollection< Person> 没有名为GenericTypeArguments的属性。

In your case, y is null since ObservableCollection<Person> does not have a property named "GenericTypeArguments".

请尝试:

var genTypeArgsProperty = typeof(Type).GetProperty("GenericTypeArguments");

var genTypeArgsValue = (Type[]) (genTypeArgsProperty.GetValue(observCol, null));

var onlyTypeArgValue = genTypeArgsValue.Single();

这篇关于反思为什么不找物业的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆