我需要编写获取类名的简单应用程序(假设该类出现在应用程序AppDomain中)并打印到控制台
all the public properties
values of each properties
all the method in the class
答案 0 :(得分:3)
var p = GetProperties(obj);
var m = GetMethods(obj);
-
public Dictionary<string,object> GetProperties<T>(T obj)
{
return typeof(T).GetProperties().ToDictionary(p=>p.Name,p=>p.GetValue(obj,null));
}
public MethodInfo[] GetMethods<T>(T obj)
{
return typeof(T).GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
}
答案 1 :(得分:1)
您可以使用调用GetValue
方法获得的PropertyInfo
GetProperties
对象方法来获取
foreach(PropertyInfo pi in myObj.GetType().GetProperties())
{
var value = pi.GetValue(myObj , null);
}
PropertyInfo
对象包含许多方法来检索你想要的关于perperty的信息,就像名字一样,是readonly ..etc
答案 2 :(得分:1)
以下是代码。 。
void Main()
{
Yanshoff y = new Yanshoff();
y.MyValue = "this is my value!";
y.GetType().GetProperties().ToList().ForEach(prop=>
{
var val = prop.GetValue(y, null);
System.Console.WriteLine("{0} : {1}", prop.Name, val);
});
y.GetType().GetMethods().ToList().ForEach(meth=>
{
System.Console.WriteLine(meth.Name);
});
}
// Define other methods and classes here
public class Yanshoff
{
public string MyValue {get; set;}
public void MyMethod()
{
System.Console.WriteLine("I'm a Method!");
}
}