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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With