为什么 .Net 将自定义属性设计为密封的最佳实践? [英] Why is .Net best practice to design custom attributes as sealed?

查看:15
本文介绍了为什么 .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 将自定义属性设计为密封的最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆