Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

เมธอด Type.GetProperties() ใน C#

เมธอด Type.GetProperties() ใน C# ใช้สำหรับดึงคุณสมบัติ (properties) ของ Type ปัจจุบัน

ไวยากรณ์

เมธอดนี้มี 2 การโหลดทับ:

public System.Reflection.PropertyInfo[] GetProperties ();
public abstract System.Reflection.PropertyInfo[] GetProperties (System.Reflection.BindingFlags bindingAttr);

พารามิเตอร์ bindingAttr คือการรวมบิตของค่าการแนมที่ระบุวิธีการค้นหา

ตัวอย่าง

ตัวอย่างการใช้งานเมธอด Type.GetProperties() กับ System.Type:

using System; 
using System.Reflection; 
public class Demo { 
    public static void Main(){ 
        Type type = typeof(System.Type); 
        PropertyInfo[] info = type.GetProperties(); 
        Console.WriteLine("Properties... "); 
        for (int i = 0; i < info.Length; i++) 
            Console.WriteLine(" {0}", info[i].ToString()); 
    } 
}

ผลลัพธ์

โค้ดจะแสดงผลรายการคุณสมบัติจำนวนมากของ System.Type

ตัวอย่างเพิ่มเติม

ตัวอย่างที่สองกับประเภท string:

using System; 
using System.Reflection; 
public class Demo { 
    public static void Main(){ 
        Type type = typeof(string); 
        PropertyInfo[] info = type.GetProperties(); 
        Console.WriteLine("Count of Properties = " + info.Length); 
        Console.WriteLine("Properties... "); 
        for (int i = 0; i < info.Length; i++) 
            Console.WriteLine(" {0}", info[i].ToString()); 
    } 
}

ผลลัพธ์

โค้ดจะแสดงผลดังนี้:

Count of Properties = 2 
Properties... 
Char Chars [Int32] 
Int32 Length