在 .NET 中,您可以使用反射来获取类的所有非继承方法吗?

问题描述:

由于这个问题此处,我正在尝试编写一个自定义 JsonConverter处理您对列表或集合进行子类化,然后向其添加额外属性的情况.因此,一种方法是忽略所有基类属性,只序列化定义类中的属性.(从技术上讲,这行不通,因为如果您继承该子类会破坏序列化,但这确实让我感到疑惑...)

Because of this issue here, I'm trying to write a custom JsonConverter that handles cases where you subclass a list or a collection, then add extra properties to it. As such, one approach would be to ignore all base-class properties and only serialize those in the defined class. (Technically this won't work because if you subclass that subclass you break the serialization, but it did make me wonder...)

是否有可能通过反射(我知道答案是是",因为 Reflector 正是这样做的,但我不知道如何)只获取在类本身上定义的成员,而不是那些定义在类上的成员遗传?例如...

Is it possible via reflection (well I know the answer is 'yes' because Reflector does exactly that, but I don't know how) to get only the members that are defined on the class itself as opposed to those that were inherited? For instance...

public class MyBaseClass
{
    public string BaseProp1 { get; set; }
    public string BaseProp2 { get; set; }
}

public class MySubClass : MyBaseClass
{
    public string SubProp1 { get; set; }
    public string SubProp2 { get; set; }
}

在这种情况下,我想反思 MySubClass 并且只得到 SubProp1SubProp2 而忽略 BaseProp1BaseProp2.所以可以这是怎么做的?

In this case, I want to reflect on MySubClass and only get SubProp1 and SubProp2 while ignoring BaseProp1 and BaseProp2. So can that be how is that done?

M

在调用GetMembers"方法获取Type的成员时,可以在绑定标志中指定DeclaredOnly".

While calling "GetMembers" method to get the members of the Type, you can specify "DeclaredOnly" in binding flag.