C# type對象


新建控制台應用程序

新建一個類

class MyClass
{
private int id;
private int age;
public int numb;
public string Name { get; set; }

private string Name1 { get; set; }
public void Test1()
{

}

public void Test2()
{

}
}

 

program里的代碼;

static void Main(string[] args)
{
//每一個類對應一個type對象 這個對象存儲了這個類有哪些方法和那些數據哪些成員
MyClass my = new MyClass() { Name="賬單"};
Type type = my.GetType();
Console.WriteLine(type.Name); //獲取類名
Console.WriteLine(type.Namespace);//獲取所在的命名空間
Console.WriteLine(type.Assembly);//獲取程序集

FieldInfo[] array = type.GetFields(); //只能獲取public字段
foreach (var item in array)
{
Console.WriteLine(item.Name);

}

PropertyInfo[] p = type.GetProperties();
foreach (var item in p)
{
Console.WriteLine(item.Name);
}

MethodInfo[] m = type.GetMethods();
foreach (var item in m)
{
Console.WriteLine(item.Name);
}
Console.WriteLine();
Console.Read();

//總結 總過type可以獲取它對應的類的所有成員(public) 除了私有
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM