What is the difference between following two implementaion,if no difference why we need Extension methods ?
(public static List<TSource> ToList<TSource>(this IEnumerable<TSource> source
);)
1.IEnumerable<Student> myExtension = mtyStudent; // "mtyStudent is colletion"
myExtension.ToList();
2.List<Student> myStudent= Enumerable.ToList(myExtension);
答案 0 :(得分:0)
There is no difference. You call the same method either way. Enumerable.ToList<TSource>(this IEnumerable<TSource> source)
is an extension method. It is simply a static method in the Enumerable
class, but you can call it like an instance method. Which is what extension methods are all about really.
答案 1 :(得分:0)
Possible duplicate of below thread:
What Advantages of Extension Methods have you found?
Main reasons are maintainability, intellisense support, compact syntax etc. Please do your research first on similar threads.
答案 2 :(得分:0)
Why extension methods are for is to extend the functionality of classes which you would otherwise not be able to do and they make using them more straightforward.
Say you have a class which you do not have direct access and you want to extend it by getting a certain value by doing some calculations based on class properties, you can do a function which takes the class as parameter, as such.
public static int GetValue(OtherGuysClass c) { ... }
You would then have to call this by
ClassX.GetValue(new OtherGuysClass());
By adding the keyword "this"
public static int GetValue(this OtherGuysClass c) { ... }
You can then call it with
new OtherGuysClass().GetValue();