溫馨提示×

如何在 C# 中使用 PropertyInfo

小樊
130
2024-07-08 16:49:15
欄目: 編程語言

在C#中,使用PropertyInfo可以訪問和操作類的屬性。以下是使用PropertyInfo的一些基本示例:

  1. 獲取屬性的值:
using System;
using System.Reflection;

class MyClass
{
    public int MyProperty { get; set; }
}

class Program
{
    static void Main()
    {
        MyClass obj = new MyClass();
        obj.MyProperty = 10;

        PropertyInfo propertyInfo = typeof(MyClass).GetProperty("MyProperty");
        int value = (int)propertyInfo.GetValue(obj);

        Console.WriteLine(value); // 輸出 10
    }
}
  1. 設置屬性的值:
using System;
using System.Reflection;

class MyClass
{
    public int MyProperty { get; set; }
}

class Program
{
    static void Main()
    {
        MyClass obj = new MyClass();

        PropertyInfo propertyInfo = typeof(MyClass).GetProperty("MyProperty");
        propertyInfo.SetValue(obj, 20);

        Console.WriteLine(obj.MyProperty); // 輸出 20
    }
}
  1. 獲取屬性的特性:
using System;
using System.Reflection;

[AttributeUsage(AttributeTargets.Property)]
class CustomAttribute : Attribute
{
    public string Description { get; }

    public CustomAttribute(string description)
    {
        Description = description;
    }
}

class MyClass
{
    [Custom("This is a custom attribute")]
    public int MyProperty { get; set; }
}

class Program
{
    static void Main()
    {
        PropertyInfo propertyInfo = typeof(MyClass).GetProperty("MyProperty");
        CustomAttribute customAttribute = (CustomAttribute)propertyInfo.GetCustomAttribute(typeof(CustomAttribute));

        Console.WriteLine(customAttribute.Description); // 輸出 "This is a custom attribute"
    }
}

通過使用PropertyInfo,您可以更靈活地訪問和操作類的屬性,從而實現更高級的功能和邏輯。

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