C#泛型类继承特性的限制

C#泛型类继承特性的限制

泛型类声明不能直接或间接使用 System.Attribute 作为基类。

A generic class declaration shall not use System.Attribute as a direct or indirect base class.

  • 直接继承 System.Attribute
// Compiler Error CS0698:
// A generic type cannot derive from 'System.Attribue' because it is an attribute class
public class B<TValue> : Attribute {}
  • 间接继承 System.Attribute
public class B : Attribute {}
// Compiler Error CS0698:
// A generic type cannot derive from 'System.Attribue' because it is an attribute class
public class C<T> : B {}

官方C#语言存储库会议笔记如下:

尽管从理论上讲这是可行的,但由于大多数运行时版本中存在 bug,因此无法正确工作(从未经过实际测试)。
我们需要一种机制来理解它适用于哪些目标运行时。我们目前也在研究这一点,因为我们在许多方面都需要这样的机制。在那之前,我们无法采用它。
结论:如果能够使足够多的运行时版本支持它,这将是下一个主要 C# 版本的候选特性。

引用

  1. Why does C# forbid generic attribute types?
    https://stackoverflow.com/questions/294216/why-does-c-sharp-forbid-generic-attribute-types

  2. Generic Attributes
    https://github.com/dotnet/csharplang/blob/main/meetings/2017/LDM-2017-02-21.md#generic-attributes

声明

内容准确性: 我会尽力确保所分享信息的准确性和可靠性,但由于个人知识有限,难免会有疏漏或错误。如果您在阅读过程中发现任何问题,请不吝赐教,我将及时更正。

posted on   wubing7755  阅读(1)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示