C# virtual 函数上的 Attribute 继承效果
环境
C# 7.3
.NETFramework 4.8
测试代码
using System;
using System.Linq;
using System.Reflection;
using static C井语法测试.MyAttribute.Type;
namespace C井语法测试
{
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
internal class MyAttribute:Attribute{
public enum Type
{
t1,
t2,
t3,
t4
}
public Type t;
public MyAttribute(Type t)
{
this.t = t;
}
}
internal class A
{
[My(t1)]
public virtual void Test(){}
}
internal class B : A
{
}
internal class C : A
{
[My(t2)]
public override void Test(){}
}
internal class D : A
{
[My(t3)]
public new void Test(){}
}
internal class E : A
{
[My(t1)]
public override void Test(){}
}
internal class F : A
{
public override void Test(){}
}
internal class Program
{
// 打印特性中的信息
private static void TestAttribute(Type classType)
{
Console.WriteLine($"class:{classType.Name}");
foreach (MethodInfo m in classType.GetMethods())
{
var atts = m.GetCustomAttributes<MyAttribute>().ToArray();
if(atts.Length == 0) continue;
Console.WriteLine($"method:{m.Name}");
foreach (var att in atts)
Console.WriteLine(att.t);
}
Console.WriteLine();
}
private static void Main(string[] args)
{
TestAttribute(typeof(A));
TestAttribute(typeof(B));
TestAttribute(typeof(C));
TestAttribute(typeof(D));
TestAttribute(typeof(E));
}
}
}
AllowMultiple=true时
class:A
method:Test
t1
class:B // 直接继承
method:Test
t1
class:C // override
method:Test
t2
t1
class:D // new
method:Test
t3
method:Test
t1
class:E // override
method:Test
t1
t1
class:F // override
method:Test
t1
AllowMultiple=false时
class:A
method:Test
t1
class:B // 直接继承
method:Test
t1
class:C // override
method:Test
t2
class:D // new
method:Test
t3
method:Test
t1
class:E // override
method:Test
t1
class:F // override
method:Test
t1
结论
class A 原函数
virtual方法上有attribute
class B 直接继承
会继承基类的Attribute
class C override 覆写基类函数 使用不一样的attribute
AllowMultiple为true时,同时存在两个attribute
AllowMultiple为false时,为新的attribute
class D new 隐藏基类函数
存在两个函数,分别有各自定义的attribute
class E override 覆写基类函数 使用一样的attribute
类似class C
class F override 不使用attribute
与基类函数的attribute一致,感觉可以视为只是替换了基类函数的函数体
注意事项
根据测试,override在AllowMultiple=true时,不能覆盖基类函数的attribute
其它
有错误请指正
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)