Is there a convenient way to map all interface methods onto a subobject?

巧了我就是萌 提交于 2019-12-24 11:17:15

问题


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();
};

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.

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?


回答1:


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

  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.



回答2:


I'd like to have that opportunity too, but I don't think it exists. Don't be afraid of doing this, though, if you really need a class that can act as both of its superclasses: it's the well-known delegation pattern (as you probably know).




回答3:


I think almost every seasoned C# developer has probably wished for this at some stage - especially those who are former Delphi developers. It's called "implementation by delegation", and it was available in Delphi.

In fact the man responsible for this Delphi feature, Steve Teixeira, now works at MSFT. Here's a blog entry where he talks about it.

Unfortunately C# can't do this as the the CLI doesn't support implementation by delegation.




回答4:


I know the pain.

So much that I've started my own project to solve this: NRoles.

This brings a form of trait (pdf) to C#.

Your code would look like this:

class FirstRole : Role {
  public void FirstMethod() { ... }
  public void SecondMethod() { ... }
}

class SecondRole : Role {
  ...
}

class MyClass : Does<FirstRole>, Does<SecondRole> {

}

You can also implement interfaces through the roles, and they'll be carried over to the composing class.



来源:https://stackoverflow.com/questions/6508465/is-there-a-convenient-way-to-map-all-interface-methods-onto-a-subobject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!