Jes*_*per 4 c# c++ generics code-reuse template-mixins
我来自C++背景,我可以使用模板mixins来编写引用FinalClass的代码,这是传入的模板参数.这允许可重用函数"混入"任何派生类,只需从ReusableMixin继承即可使用MyFinalClass的模板参数.这一切都被内联到课堂中,所以就好像我只是写了一个大课程来做所有事情 - 即非常快!由于mixins可以链接,我可以将各种行为(和状态)混合到一个对象中.
如果有人想要澄清这项技术,请询问.我的问题是,如何在C#中重用?注意:C#泛型不允许从泛型参数继承.
Jon*_*son 12
您可以使用接口和扩展方法.例如:
public interface MDoSomething // Where M is akin to I
{
// Don't really need any implementation
}
public static class MDoSomethingImplementation
{
public static string DoSomething(this MDoSomething @this, string bar) { /* TODO */ }
}
Run Code Online (Sandbox Code Playgroud)
现在,您可以通过继承MDoSomething来使用mixins.请记住,在(this)类中使用扩展方法需要使用此限定符.例如:
public class MixedIn : MDoSomething
{
public string DoSomethingGreat(string greatness)
{
// NB: this is used here.
return this.DoSomething(greatness) + " is great.";
}
}
public class Program
{
public static void Main()
{
MixedIn m = new MixedIn();
Console.WriteLine(m.DoSomething("SO"));
Console.WriteLine(m.DoSomethingGreat("SO"));
Console.ReadLine();
}
}
Run Code Online (Sandbox Code Playgroud)
HTH.
| 归档时间: |
|
| 查看次数: |
1014 次 |
| 最近记录: |