访问与反思抽象类的属性 [英] Access to properties of abstract class with reflection

查看:128
本文介绍了访问与反思抽象类的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个抽象类 - 让我们将其命名为基本。这个类包含一些属性。此外,我还有一个类,从类继承基本 - 让我们将其命名为儿童儿童不是抽象的。

I have an abstract class — let's name it Base. This class contains some properties. Moreover, I have another class, inherited from class Base — let's name it Child. Child is not abstract.

我想从类访问属性基础与反思,和基本宣布这些属性。

I want to access the properties from class Base with Reflection, and only those properties declared in Base.

下面的代码当然是不可能的,因为我不能创建一个抽象类的实例

The following code is of course not possible, because I can't create an instance of an abstract class

Base base = new Base();
Type type = base.GetType();
PropertyInfo[] propInfos =
    type.GetProperties(
        BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly
    );



下面的代码是可能的,但我得到的所有属性,这些在定义基本以及那些在儿童定义

Child child = new Child();
Type type = child.GetType();
PropertyInfo[] propInfos =
    type.GetProperties(BindingFlags.Instance | BindingFlags.Public);



我怎样才能获得类的所有属性基本通过反射?

推荐答案

中调用的GetType()上的对象是只有得到一个键入目标的途径之一。另外,它甚至对抽象作品类,为 typeof运算()。使用 BindingFlags.DeclaredOnly 选项与 typeof运算(A).GetProperties 应该做的伎俩。

Invoking GetType() on an object is only one of the ways of getting a Type object. Another, which works even for abstract classes, is typeof(). Using the BindingFlags.DeclaredOnly option with typeof(A).GetProperties should do the trick.

这篇关于访问与反思抽象类的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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