开发者

How to determine if a field has 'new' modifier via reflection? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

How do I detect the "new" modifer on a field using reflection?

开发者_Go百科

Having the following declaration

public class B : A
{
    public new string Name;
}

how do i determine if the field has 'new' modifier for its FieldInfo instance?


For fields, no such exists; the IL is simply:

.field public string Name

etc - since there is no concept of virtual fields or newslot etc. The new modifier here exists purely for the compiler, for you to assert that you acknowledge you are doing something a little bit confusing. Adding the new here will suppress a compiler warning (CS0108), but does not change the IL. As such, you cannot distinguish between a formally newd field vs a field that has been hidden without new.

It would be preferable, though, if you limited yourself to private fields with public accessor properties. And note that in either event: the field in the base type still exists.


I think you'll need to search the base-classes hierarchy for a member with the same name, and if it isn't, then it is new.

I know it's ugly, but as per the comment on this other answer to the same question How do I detect the "new" modifer on a field using reflection?, it says:

I took a look at ILSpy's source code, they are doing the same thing - walking the inheritance chain. They are using Mono.Cecil, but there is no special info that's unavailable via reflection. For more information, take a look at ILSpy's AstBuilder.SetNewModifier method.

Probably not what you have been expecting, sorry for that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜