有没有一种简便的方法来映射所有的接口方法到子对象? [英] Is there a convenient way to map all interface methods onto a subobject?

查看:131
本文介绍了有没有一种简便的方法来映射所有的接口方法到子对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我需要从C#两个类继承。这是不允许的,所以我可以做到以下几点:从类之一继承,并包括其他类的成员变量,从接口继承并重新实现这些接口的所有方法通过重定向到他们的成员变量:

Suppose I need to inherit from two classes in C#. This is not allowed, so I can do the following: inherit from one of the classes and include the other class as a member variable, inherit from its interfaces and reimplement all methods of those interfaces by redirecting them onto that member variable:

interface SecondBaseInterface {
    void FirstMethod();
    void SecondMethod();
};

class MyClass : FirstBaseClass, SecondBaseInterface {

   public void FirstMethod()
   {
      secondBase.FirstMethod();
   }

   public void SecondMethod()
   {
      secondBase.SecondMethod();
   }

   SecondBaseClass secondBase = new SecondBaseClass();
};

现在这个工程,但如果有很多的方法, SecondBaseInterface 这将需要大量的code打字,其实没有任何用处,我会必须维护code的情况下 SecondBaseInterface 的变化。

now this works, but if there's a lot of methods in SecondBaseInterface it will require lot of typing of code that in fact does nothing useful and I'll have to maintain that code in case SecondBaseInterface changes.

有一些C#的功能,会告诉编译器的 SecondBaseInterface 的所有方法,请拨打相应的该成员变量的方法或其他方便的方式做如此大规模重定向?

Is there some C# feature that would tell the compiler "for all methods of SecondBaseInterface please call corresponding methods of this member variable" or some other convenient way to do such massive redirection?

推荐答案

有没有简单的语言功能,浮现在脑海,这里有一些想法:

There is no simple language feature that springs to mind, here are a few ideas:

  1. 使用.NET4.0 DynamicObject ,在那里你可以在飞行中添加属性/成员。
  2. 使用面向方面Priogramming,或IL织造添加一个mixin。请参见 PostSharp 例如。
  3. 使用某种形式的code一代,例如 ReSharper的
  1. Use .NET4.0 DynamicObject, where you can add properties / members on the fly.
  2. Use Aspect Oriented Priogramming, or IL Weaving to add a mixin. See PostSharp for example.
  3. Use some form of code generation, e.g. ReSharper.

这篇关于有没有一种简便的方法来映射所有的接口方法到子对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆