C# 对象扩展方法
在 Object 类上使用扩展方法是个好主意吗?
我想知道注册此方法是否会导致性能损失,因为它将加载到上下文中加载的每个对象上。
Is it a good idea to use an extension method on the Object class?
I was wondering if by registering this method if you were incurring a performance penalty as it would be loaded on every object that was loaded in the context.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
除了另一个答案之外:
不会有性能损失,因为扩展方法是编译器功能。考虑以下代码:
对
MyMethod
的调用将实际编译为:In addition to another answers:
there would be no performance penalty because extension methods is compiler feature. Consider following code:
The call to
MyMethod
will be actually compiled to:不会有性能损失,因为它不会附加到系统中的每种类型,它只能在系统中的任何类型上调用。所发生的只是该方法将显示在智能感知中的每个单个对象上。
问题是:您真的需要将其放在对象上吗,还是可以更具体。如果它需要在对象上,则将其制作为对象。
There will be no performance penalty as it doesn't attach to every type in the system, it's just available to be called on any type in the system. All that will happen is that the method will show on every single object in intellisense.
The question is: do you really need it to be on object, or can it be more specific. If it needs to be on object, the make it for object.
如果您确实打算扩展每个对象,那么这样做是正确的。但是,如果您的扩展实际上仅适用于对象的子集,则应将其应用于必要的最高层次结构级别,但仅此而已。
此外,该方法仅在导入命名空间的情况下可用。
我已经扩展了
Object
来尝试转换为指定类型的方法:我还重载了它以接受
success
bool (如TryParse
确实):我已经将其扩展为也尝试解析输入(通过使用ToString并使用转换器),但这变得更加复杂。
If you truly intend to extend every object, then doing so is the right thing to do. However, if your extension really only applies to a subset of objects, it should be applied to the highest hierarchical level that is necessary, but no more.
Also, the method will only be available where your namespace is imported.
I have extended
Object
for a method that attempts to cast to a specified type:I also overloaded it to take in a
success
bool (likeTryParse
does):I have since expanded this to also attempt to parse
input
(by usingToString
and using a converter), but that gets more complicated.是的,在某些情况下,事实上这是一个好主意。在 Object 类上使用扩展方法不会造成任何性能损失。只要您不调用此方法,应用程序的性能就不会受到影响。
例如,考虑以下扩展方法,它列出给定对象的所有属性并将其转换为字典:
Yes, there are cases where it is a great idea in fact.Tthere is no performance penalty whatsoever by using an extension method on the Object class. As long as you don't call this method the performance of your application won't be affected at all.
For example consider the following extension method which lists all properties of a given object and converts it to a dictionary:
下面的示例演示了正在使用的扩展方法。
以下示例演示了如何使用此方法。
The following example demonstrates the extension method in use.
The following example demonstrates how this method can be used.