开发者

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

开发者 https://www.devze.com 2023-03-16 10:10 出处:网络
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, in开发者_Go百科herit

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, in开发者_Go百科herit 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?


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.


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).


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号