In C #, does it matter to define class members at runtime?

Suppose I have a class called foo, and it has 3 public members foo1, foo2, and foo3.

Now suppose I write a function that takes an instance of the foo class as a parameter, but when I write this function, I have no idea what its public members have.

Is there a way to determine at runtime that it has public members foo1, foo2, foo3 AND ONLY foo1, foo2, foo3. IE - find out what all public members are?

And can I also determine their types?

+3
source share
6 answers

Well, this is what Reflection exists for:

Type myObjectType = typeof(foo);

System.Reflection.FieldInfo[] fieldInfo = myObjectType.GetFields();
foreach (System.Reflection.FieldInfo info in fieldInfo)
   Console.WriteLine(info.Name); // or whatever you desire to do with it
+6
source

You can use reflection:

// List all public properties for the given type
PropertyInfo[] properties = foo.GetType().GetProperties();
foreach (var property in properties)
{
    string propertyName = property.Name;
}

, , .

+3

. , :

myFoo.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public);

, . , . , GetFields(...), GetProperties(...) ..

Type, #.

+2
foreach(PropertyInfo pi in yourObject.GetType().GetProperties())
{
   Type theType = pi.PropertyType;
}
0
0

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


All Articles