c# - Consume Extension method in non-static class -
all of examples extension methods have seen consume extension method in class like:
class program { static void main() { ...call extension method here } }
these seem work because consuming class static. there way consume extension method in non static class below? can't seem find examples this.
i have extension method class:
using system; using system.collections.generic; namespace awesomeapp { public static class linqextensionmethods { public static ienumerable<t> finditemsbeforeandafter<t>(this ienumerable<t> items, predicate<t> matchfilling) { if (items == null) throw new argumentnullexception("items"); if (matchfilling == null) throw new argumentnullexception("matchfilling"); return items; } } }
and have class consumes extention method
namespace awesomeapp { public class leaders : ileaders { var leaders = getallleaders(); var orderedleaders = leaders.orderbydescending(o => o.pointsearned); var test = orderedleaders.finditemsbeforeandafter(w => w.userid == 1); } }
if call extension method static class not the 'extension method must defined in non-generic static class' error:
public class test { public void testfunc() { list<int> testlist = new list<int>() {1,2,3,4,5,6,7,8,9}; testlist.finditemsbeforeandafter<int>(e => e == 5); } }
i have read through stackoverflow answers can find on non-generic static class error , deal writing extension method don't deal consuming it.
so question is: if using extension method non-static class not possible there way works in similar way? example can called .extensionmethod not helper.extensionmethod(passedobject)??
resolution: thought cut , pasted extension method public class leaders : ileaders own class make static copied it. compiler error pointing class name did not see extension method still @ bottom of file. error message accurate , answered correct.
these seem work because consuming class static.
no, that's incorrect. extension methods don't have consumed static classes or static methods.
however, have declared in class is:
- non-nested
- non-generic
- static
you appear confusing calling declaring - when say:
if call extension method static class not the 'extension method must defined in non-generic static class' error
... you'll if try declare method in class doesn't satisfy above criteria. should double click on error show it's being generated - i'm sure you'll find it's declaration, not use of method.
note final example (class test
) not static class, nor static method.
Comments
Post a Comment