How to list fields of the 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 the second syntax?

+3
source share
4 answers

You do not need to typeof()call around GetType, as it already returns a Type object. typeof- special syntax for getting an object Typeon behalf of a type, without having to do something like Type.GetType("Foo").

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

typeof System.Type. typeof - , (, Int32 object MyClass)), System.Type. , GetType, System.Type.

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

typeof. :

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

typeof - "" Type. GetType() , .

, , ... :

string x = "y.ToString()";

string x = y.ToString();

typeof(), ...

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

Source: https://habr.com/ru/post/1788675/


All Articles