溫馨提示×

c#反射怎么獲取屬性類型

c#
小億
151
2024-10-27 00:21:31
欄目: 編程語言

在C#中,使用反射可以獲取屬性的類型。以下是一個示例代碼,展示了如何使用反射獲取類型的屬性及其類型:

using System;
using System.Reflection;

class Program
{
    static void Main()
    {
        // 創建一個示例類
        Type type = typeof(ExampleClass);

        // 獲取類的所有屬性
        PropertyInfo[] properties = type.GetProperties();

        // 遍歷屬性并輸出屬性名及其類型
        foreach (PropertyInfo property in properties)
        {
            Console.WriteLine($"Property Name: {property.Name}, Property Type: {property.PropertyType}");
        }
    }
}

class ExampleClass
{
    public string MyString { get; set; }
    public int MyInt { get; set; }
    public DateTime MyDateTime { get; set; }
}

在這個示例中,我們首先使用typeof關鍵字獲取ExampleClass類型的Type對象。然后,我們使用GetProperties()方法獲取類的所有屬性。最后,我們遍歷屬性數組并輸出每個屬性的名稱和類型。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女