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...)
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; }
}
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
A lot of reflection functions accept a parameter of type BindingFlags. This enumeration includes a value DeclaredOnly:
MemberInfo.DeclaringType
should do what you need. To get members directly defined in type X filter the members byDeclaringType == typeof(X)
.You have to select all members in
MySubClass
and keep only those whereDeclaringType == MySubClass
.With LINQ, something like that (overkill) :
Or with
GetMembers()
overload :While calling "GetMembers" method to get the members of the Type, you can specific "DeclaredOnly" in binding flag.