如何从任何.net类获取所有公共属性和方法?

时间:2012-05-17 15:05:50

标签: c#

我需要编写获取类名的简单应用程序(假设该类出现在应用程序AppDomain中)并打印到控制台

 all the public properties 
 values of each properties 
 all the method in the class 

3 个答案:

答案 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

http://msdn.microsoft.com/en-us/library/b05d59ty.aspx

答案 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!");
    }


}
相关问题