in C#, Is there anyway to determine a class's members at runtime?

孤街醉人 提交于 2020-01-03 20:05:13

问题


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

Now suppose I'm writing a function that takes an instance of class foo as a parameter, but when I'm writing this function I have no idea what public members it has.

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

And can I also determine their types?


回答1:


Well, that's what Reflection is there 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



回答2:


You could use reflection:

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

You should be aware that there could be an additional overhead when using reflection because types are evaluated at runtime.




回答3:


Have a look at the .net reflection namespace:

http://msdn.microsoft.com/en-us/library/ms173183(VS.80).aspx




回答4:


This is a job for reflection. Look into methods like:

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

This will return all public, instance methods that the type has. You can then look through the returned results and determine if this class meets your criteria. There are equivalent methods as well for other types of members, such as GetFields(...), GetProperties(...), etc.

Basically you want to get to know the Type class, which is the core of C#'s reflection capabilities.




回答5:


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



回答6:


Following article on MSDN should help you determine the methods of a type



来源:https://stackoverflow.com/questions/3196504/in-c-is-there-anyway-to-determine-a-classs-members-at-runtime

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!