简体   繁体   中英

How to list fields of current class in C# Reflection (problem with this.GetType())?

This is accepted by the compiler:

FieldInfo[] fieldInfos;
fieldInfos = typeof(MyClass).GetFields(BindingFlags.NonPublic | BindingFlags.Instance);

This is NOT accepted by the compiler:

FieldInfo[] fieldInfos;
fieldInfos = typeof(this.GetType()).GetFields(BindingFlags.NonPublic | BindingFlags.Instance);

How to fix second syntax?

You don't need typeof() around a GetType call since it already returns a Type object. typeof is a special syntax for getting a Type object from a type name, without having to do something like Type.GetType("Foo") .

FieldInfo[] fieldInfos;
fieldInfos = GetType().GetFields(BindingFlags.NonPublic |
                                 BindingFlags.Instance);

typeof does not permit you to pass in an instance of System.Type . typeof is an operator whose sole parameter is a type (like Int32 , or object , or MyClass ) and it returns an instance of System.Type . When you already have an instance of an object, just call GetType so get an instance of System.Type . Therefore, just say

fieldInfos = this.GetType()
                 .GetFields(BindingFlags.NonPublic | BindingFlags.Instance);

You don't need the typeof in the second example. Just use:

 FieldInfo[] fieldInfos = this.GetType().GetFields(BindingFlags.NonPublic |
                                                   BindingFlags.Instance);

The point of typeof is it's a sort of "literal" format for obtaining a Type reference. GetType() already returns a type, so you don't need it.

To put it another way, suppose you wanted a string... you wouldn't use:

string x = "y.ToString()";

you'd just use

string x = y.ToString();

Replace the quotes with typeof() and it's the same sort of thing...

FieldInfo[] fieldInfos = this.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM