I need a parameter that implements multiple interfaces,How should the code be represented?

卡卡 1 Reputation point
2020-12-04T10:47:17.157+00:00

interface IA
{
int DoA();
}
interface IB
{
int DoB();
}

These are two interfaces. My method needs to implement the parameters of both interfaces. Is there any way to restrict the caller?
I've thought about a lot of things That I can think of.
For example,

1: use the generic
int MyMethod<T>(T x)where T:IA,IB
It feels ok,but what is the point of generics for this method if the caller will always just treat the class as a parameter and never use the structure?

2:
int MyMethod(IA x)
{
The IB temx = x (IB);
...
}
I don't think this is the best.
//============================
so is there a way for the compiler to restrict the caller?
(By the way, why are delegates designed as classes and not structs?)

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,997 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Collin Brittain 36 Reputation points
    2020-12-04T17:52:36.6+00:00

    You could make a third interface IC that implements both interfaces and use it as your parameter.

    `interface IC : IA, IB
    {

    }`

    public int MyMethod(IC myParameter)
    {
         // Do something
    }
    

    Now the methods and properties of both interfaces are available to you in the MyMethod method.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.