An extension method is still a static method. You can use it exactly as you'd use a normal static method.
The only difference is that an extension method allows you to use the method in a way that looks like it's part of the type, so you can write:
int result = stringValue.BMethod();
Instead of:
int result = BClass.BMethod(stringValue);
This works purely as a compile "trick" - the compiler sees the first form, and if the BClass
is usable (it has a proper using
and is in a referenced assembly), then it will turn it into the second method's IL for you. It's purely a convenience.
Which is proposed ?
This really depends. If you control the type, I'd recommend putting the methods on the type itself. This is typically more maintainable.
If you don't control the type, or you're trying to "extend" a common type (such as IEnumerable<T>
), then extension methods may be a reasonable approach.
However, if the type is a very common type, I'd typically avoid extension methods, as they become "noise" in intellisense, which in turn can cause extra confusion. For example, I would personally not recommend adding extension methods on System.Object
or System.String
, etc.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…