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

如何从基类调用GetCustomAttributes?

从基类调用 GetCustomAttributes 的方法是通过反射。在 C# 中,可以使用 System.Reflection 命名空间中的 GetCustomAttributes 方法来获取自定义属性。以下是一个简单的示例:

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

// 自定义属性
public class CustomAttribute : Attribute
{
    public string Value { get; set; }
}

// 基类
public class BaseClass
{
    [CustomAttribute(Value = "Base Class")]
    public virtual void Method()
    {
        Console.WriteLine("Base Class Method");
    }
}

// 派生类
public class DerivedClass : BaseClass
{
    [CustomAttribute(Value = "Derived Class")]
    public override void Method()
    {
        Console.WriteLine("Derived Class Method");
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        // 获取派生类的 Method 方法
        MethodInfo methodInfo = typeof(DerivedClass).GetMethod("Method");

        // 获取基类的 Method 方法
        MethodInfo baseMethodInfo = methodInfo.GetBaseDefinition();

        // 获取基类的自定义属性
        object[] baseAttributes = baseMethodInfo.GetCustomAttributes(typeof(CustomAttribute), true);

        // 输出基类的自定义属性
        foreach (CustomAttribute attribute in baseAttributes)
        {
            Console.WriteLine($"Base Class Attribute Value: {attribute.Value}");
        }
    }
}

在这个示例中,我们定义了一个自定义属性 CustomAttribute,并在基类和派生类的 Method 方法上使用了这个属性。然后,我们通过反射获取了派生类的 Method 方法,并使用 GetBaseDefinition 方法获取了基类的 Method 方法。最后,我们使用 GetCustomAttributes 方法获取了基类的自定义属性,并输出了它们的值。

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

相关·内容

15分34秒

第十九章:字节码指令集与解析举例/52-方法调用指令

2时0分

看见新力量——用数字之笔描绘新形势下的产融结合之道

6分6秒

普通人如何理解递归算法

14分54秒

最近我收到了 SAP 上海研究院一个部门领导的邀请,参加了一个信息素养故事分享会。我也就"如何快速上

4分10秒

英语不好,对 SAP 英文文档有所畏惧,该怎么办?

领券