在.NET中,可以使用反射来获取类的所有非继承方法吗?
由于这个问题此处,我正在尝试编写一个自定义 JsonConverter 来处理以下情况您可以对列表或集合进行子类化,然后向其添加额外的属性。因此,一种方法是忽略所有基类属性并仅序列化已定义类中的那些属性。 (从技术上讲,这是行不通的,因为如果你对该子类进行子类化,就会破坏序列化,但这确实让我想知道......)
是否可以通过反射(我知道答案是“是”,因为 Reflector 正是这样做的,但是我不知道如何)只获取类本身定义的成员而不是继承的成员?例如......
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
并只获得 SubProp1
和 SubProp2
而忽略 BaseProp1
代码>和BaseProp2
。那么可以吗 这是怎么做到的?
中号
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在调用
GetMembers()
方法获取Type的成员时,您可以在绑定标志中指定DeclaredOnly
。While calling
GetMembers()
method to get the members of the Type, you can specifyDeclaredOnly
in binding flag.您必须选择
MySubClass
中的所有成员,并仅保留DeclaringType == MySubClass
的成员。使用 LINQ,类似的东西(过度杀伤):
或者使用
GetMembers()
重载:You have to select all members in
MySubClass
and keep only those whereDeclaringType == MySubClass
.With LINQ, something like that (overkill) :
Or with
GetMembers()
overload :许多反射函数接受 BindingFlags 类型的参数。此枚举包含一个值 DeclaredOnly:
A lot of reflection functions accept a parameter of type BindingFlags. This enumeration includes a value DeclaredOnly:
MemberInfo.DeclaringType
应该做你需要的事情。要获取直接在类型 X 中定义的成员,请通过 DeclaringType == typeof(X) 过滤成员。MemberInfo.DeclaringType
should do what you need. To get members directly defined in type X filter the members byDeclaringType == typeof(X)
.只需使用这个标志:
Just use this Flags :