简体   繁体   English

C#中扩展方法和方法的区别

[英]Difference between Extension methods and Methods in C#

C#中的Extension MethodsMethods什么区别?

I think what you are really looking for is the difference between Static and Instance Methods 我认为你真正想要的是静态和实例方法之间的区别

At the end of the day Extension methods are some nice compiler magic and syntactic sugar that allow you to invoke a Static method as though it were a method defined on that particular class instance. 在一天结束时,扩展方法是一些很好的编译器魔术和语法糖,允许您调用静态方法,就像它是在特定类实例上定义的方法一样。 However, it is NOT an instance method, as the instance of that particular class must be passed into the function. 但是,它不是实例方法,因为必须将该特定类的实例传递给函数。

ExtensionMethods : Let you define set of methods to a class without subclassing another benefit over inheritance. ExtensionMethods:让您为类定义方法集,而不继承继承的另一个好处。

Methods : They are used for implementation of operation defind for the the class. 方法:它们用于实现类的操作定义。

See example of Extension Methods 请参阅扩展方法示例

One really nice feature of extension methods is that they can be called on null objects, see this: 扩展方法的一个非常好的功能是可以在null对象上调用它们,请参阅:

myclass x = null;
x.extension_method(); // this will work
x.method(); // this won't

It is a pity, that for example most methods of string are not extension methods, after all 遗憾的是,例如,大多数字符串方法都不是扩展方法

x.ToLower();

should return null if x is null. 如果x为null,则应返回null。 I mean, it would be useful. 我的意思是,它会很有用。

When I need such null-transparency I prefer writing extension methods. 当我需要这种空透明度时,我更喜欢编写扩展方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM