为什么反射没有找到属性 [英] Why reflection does not find property

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

问题描述

我有类:

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

如果是curios,为什么我需要这个功能点击这里

In case of curios why I needed that functionality click here

推荐答案

我真的不明白你想要完成的所有这些meta-meta反思,但你似乎误解了什么 Type.GetProperty 做。它获取由 System.Type 实例(在这种情况下为)表示的实际类型的属性的元数据的ObservableCollection<人> )。它不 > 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 为空,因为 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天全站免登陆