如何在 C# 中使用 PropertyInfo

   2024-10-07 8130
核心提示:在C#中,使用PropertyInfo可以访问和操作类的属性。以下是使用PropertyInfo的一些基本示例:获取属性的值:using System;using S

在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,您可以更灵活地访问和操作类的属性,从而实现更高级的功能和逻辑。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号