简体   繁体   中英

c#: any way to define an argument with both class and interface type?

I'm essentially trying to find something like generic constraints for regular arguments, something like:

public void foo( Bar x) where x : ISomething {//code that calls functionality from both Bar and ISomething. }

In a simple case like this however, I can simply create a class that extends Bar and implements ISomething, using that as the type for the argument.

This seems to break down when multiple interfaces are involved, since an intermediate class would be needed for each relevant combination of interfaces, even if the implementation would have to be defined in derived classes anyways.

Is this just one of those cases where I have to suck it up and deal with it or is there an elegant way to accomplish this.

Generics can have multiple constraints, forcing the caller to implement all of them. But without needing you to specify what that type looks like. For example;

public void foo<T>(T x) where T : ISomething, Bar {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM