首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

c#如何从PropertyInfo获取base.Name

在 C# 中,PropertyInfo 类可以用于获取属性的元数据。要从 PropertyInfo 获取基类的属性名称,可以使用 PropertyInfo.DeclaringType 属性来获取声明该属性的类型,然后使用 Type.BaseType 属性来获取基类。以下是一个示例:

代码语言:csharp
复制
using System;
using System.Reflection;

class BaseClass
{
    public string BaseProperty { get; set; }
}

class DerivedClass : BaseClass
{
    public string DerivedProperty { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        PropertyInfo derivedPropertyInfo = typeof(DerivedClass).GetProperty(nameof(DerivedClass.DerivedProperty));
        PropertyInfo basePropertyInfo = typeof(BaseClass).GetProperty(nameof(BaseClass.BaseProperty));

        Console.WriteLine($"Derived property name: {derivedPropertyInfo.Name}");
        Console.WriteLine($"Base property name: {basePropertyInfo.Name}");
    }
}

在这个示例中,我们首先获取了 DerivedClass 类的 DerivedProperty 属性的 PropertyInfo 对象,然后获取了 BaseClass 类的 BaseProperty 属性的 PropertyInfo 对象。最后,我们分别输出了这两个属性的名称。

需要注意的是,这个示例中的 PropertyInfo.Name 属性返回的是属性的名称,而不是属性的完整名称(包括命名空间和类型名称)。如果需要获取完整的属性名称,可以使用 PropertyInfo.DeclaringType.FullName 属性来获取声明该属性的类型的完整名称,然后将属性名称与之连接。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券