Why is .Net best practice to design custom attributes as sealed?(为什么 .Net 将自定义属性设计为密封的最佳实践?)
问题描述
我正在阅读 Andrew Troelsen 的 Pro C# 2010 和 .Net 4 平台.
I'm reading Pro C# 2010 and the .Net 4 Platform by Andrew Troelsen.
在第 15 章关于属性有一个注释:
In Chapter 15 about Attributes exists a note:
注意:出于安全原因,将所有自定义属性设计为密封的被认为是 .Net 最佳实践.
Note: For security reasons, it is considered a .Net best practice to design all custom attributes as sealed.
作者没有解释为什么,谁能解释一下?
The author doesn't explain why, can someone explain why?
推荐答案
CA1813:避免未密封的属性:.NET Framework 类库提供检索方法自定义属性.默认情况下,这些方法搜索属性继承层次结构;例如 Attribute.GetCustomAttribute搜索指定的属性类型,或任何属性类型扩展指定的属性类型.封印属性消除通过继承层次结构搜索,可以改进性能.
CA1813: Avoid unsealed attributes: The .NET Framework class library provides methods for retrieving custom attributes. By default, these methods search the attribute inheritance hierarchy; for example Attribute.GetCustomAttribute searches for the specified attribute type, or any attribute type that extends the specified attribute type. Sealing the attribute eliminates the search through the inheritance hierarchy, and can improve performance.
参考:https://docs.microsoft.com/visualstudio/code-quality/ca1813-avoid-unsealed-attributes
属性只是在运行时发现的元数据.正如引用的那样,如果其他人从您的自定义属性类派生,默认情况下 .NET 也会找到它们,如果派生的属性类以您从未想过的方式修改原始属性的行为,这可能意味着安全风险到.
Attributes are simply metadata discovered at runtime. As it is quoted, if someone else derives from your custom attribute class, by default .NET will find them too, which may imply a security risk if the derived attribute class is modifying the behavior of your original attribute in a way to you never intended to.
尽管性能是密封属性类的主要原因,但这里有一个 关于其安全方面的强大文章.
Even though performance is the prime reason to seal attribute classes, here is a formidable article dealing with its security side.
这篇关于为什么 .Net 将自定义属性设计为密封的最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 .Net 将自定义属性设计为密封的最佳实践?
基础教程推荐
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
