Which interacts with one class?

From the code, how can we find out which interfaces a single class implements?

Example:

interface IDrink
interface IEat

class Milk : IDrink    
class Water: IDrink    
class Potato: IEat

I want to know if IDrink Potato implements or not. How can i do this?

.

Using this:

I have one method that gets one " object myObject", and I need to see if I drop it with IDrink or IEat.

+3
source share
5 answers

You can either throw it (which may throw an exception) or use the operator as.

private void DrinkIt(Object o) {
    IDrink possibleDrink = o as IDrink;

    if (possibleDrink == null)
        Console.WriteLine("Not a drink!");
    else {
        ChugItDown(possibleDrink);
        Console.WriteLine("That hit the spot!");
    }
}

It doesn't matter how many interfaces are oimplemented - here you are just wondering if that is IDrink. If you want a complete list, you should use reflection ( System.Reflection):

Type [] interfaces = myObject.GetType().GetInterfaces();

, myObject null - null . , interfaces IDrink, IEat ..

+10

, is:

if (myObject is IEat)
   //It looks like food
+7

as:

void Method(Object myObject) {
  IDrink drink = myObject as IDrink;
  if (drink != null) {
    // Use the IDrink interface.
  }
}

, is:

void Method(Object myObject) {
  if (myObject is IDrink) {
     // ...
  }
}
+2

- :

typeof(IDrink).IsInstanceOf(myObject)

. MSDN : http://msdn.microsoft.com/en-us/library/system.type.isinstanceoftype.aspx

UPDATE

:

public interface IDrink{}
public interface IEat{}

public class Milk : IDrink{}
public class Water: IDrink  {}
public class Potato : IEat { }


class Program
{
    static void Main(string[] args)
    {
        object milk = new Milk();
        Console.WriteLine("Is Milk an IDrink: {0}",
            typeof(IDrink).IsInstanceOfType(milk));
        Console.WriteLine("Is Milk an IEat: {0}",
            typeof(IEat).IsInstanceOfType(milk));

        Console.ReadLine();
    }
}

outputs the result:

Milk IDrink: True Is Milk IEat: False

+1
source

Source: https://habr.com/ru/post/1716986/


All Articles