在C#中,使用PropertyInfo可以訪問和操作類的屬性。以下是使用PropertyInfo的一些基本示例:
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
}
}
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
}
}
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,您可以更靈活地訪問和操作類的屬性,從而實現更高級的功能和邏輯。