How to write extension method that work with base class
<p>Idea is to have extension method that extend my functionality.</p><p>So instead of having something like this:</p><pre><br /><code> return Add(Add(storage.GetFirst(), 3), 7);<br /></code><br /></pre><p>I want have something like this:</p><pre><br /><code>return storage.GetFirst().Add(3).Add(7);<br /></code><br /></pre><p>Problem with extension methods is that they have to be static in static class. This is simplify example of what I want to do.</p><pre><br /><code> public class Storage<br /> {<br /> public int GetFirst()<br /> {<br /> return 100;<br /> }<br /> public int GetAll(int x, int y)<br /> {<br /><br /> // ... <br /> return x + y;<br /> }<br /> }<br /> public abstract class MyBase<br /> {<br /> protected Storage storage;<br /> protected MyBase()<br /> {<br /> storage = new Storage();<br /> }<br /><br /> public int Add(int what, int howMuch)<br /> {<br /> return storage.GetAll(what, howMuch);<br /> }<br /><br /> }<br /><br /> public class MyClass : MyBase<br /> {<br /> public int method1()<br /> {<br /> return Add(Add(storage.GetFirst(), 3), 7);<br /><br /> //I want have something like this:<br /> // return storage.GetFirst().Add(3).Add(7);<br /> }<br /> }<br /></code><br /></pre><p>Off course classes Storage, MyBase and MyClass must not be static. Logic is simplify to have clean and simple example so relation between classes must stay same. What I want to do is to make Add method to be extension method, but leave everything else "more less same".</p><p>Is this possible to do and how?</p><br /><h2>Click here view more answers <a href="%20http://stackoverflow.com/questions/34525879/how-to-write-extension-method-that-work-with-base-class">http://ift.tt/1VpgoWj</a></h2>
Nhận xét
Đăng nhận xét