开发者

What is interface casting for in C#?

开发者 https://www.devze.com 2023-03-05 05:40 出处:网络
I do understand how writing an interface works in C#, as for example described here: codeguru explanation

I do understand how writing an interface works in C#, as for example described here: codeguru explanation

interface IIntelligence
   {
      bool intelligent_behavior();
   }

   class Human: IIntelligence
   {
      public Human()
      {
          //.............
      }

/// Interface method definition in the class that implements it
      public bool intelligent_behavior()
      {
         Console.WriteLine("........");
         return true
      }
   }

I am however confused about the following process of interface casting:

Human human = new Human();
// The human object is casted to the interface type
IIntelligence humanIQ = (IIntelligence)human;
humanIQ.intelligent_behavior();

What is the sense of having a class (Human in this case) implement an interface, and then casting its instance human back to the interface? The question is not how it works, but why开发者_StackOverflow it is done.


.net offers two types of interface implementations implicit implementation and explicit implementation.

When you are using implicit implementation , it will become part of the type interface itself for example if you have a IPerson interface like this :

public interface IPerson
{
string Name{get;}
}

and you implement it as follows :

public class Person:IPerson
{
public string Name{get; ....}
}

you can access it like this (implicitly):

aPerson.Name;

but if you implement it like this (explicitly) :

public class Person:IPerson
{
string IPerson.Name{get; ....} // notice that there's no need to include access modifier.
}

Then it can only be accessed using IPerson interface:

((IPerson)aPerson).Name;

UPDATE:

Actually ,explicit interface implementation allow us to implement different interfaces with members that have same name.(as shown in this Tutorial)


Sometimes you may not know what an object is, but you know that it implements a certain Interface.


A brief and popular example. We can implement such code: interface IIntelligence { string Talk(); }

   class Cat: ICreature
   {
      public string Talk()
      {
         Console.WriteLine("Meow!");
         return true
      }
   }

   class Dog: ICreature
   {
      public string Talk()
      {
         Console.WriteLine("Arf!");
         return true
      }
   }

   class Human: ICreature
   {
      public string Talk()
      {
         Console.WriteLine("Hello!");
         return true
      }
   }

And then we can use following code:

ICreature() creatures = new ICreature(){new Human(), new Dog(), new Cat()};
foreach(IIntelligence creature in creatures){
  Console.WriteLine(creature.Talk());
}

For more detailed information, see "Polymorphism in object-oriented programming" in google.


It's to get access to explicit interface implementation.

Sometimes you want to hide the fact that a class implements an interface. This is done by implementing the interface explicitly.

public class MyClass : IInterface
{
     string IInterface.TheMethod(){}
}


For the same reason you'd cast a derived class back to it's base class.


Consider this situation. I've added a method to your example.

interface IIntelligence
{
    bool intelligent_behavior();
}

class Human: IIntelligence
{
    public Human() { }  

    /// Interface method definition in the class that implements it
    public bool IIntelligence.intelligent_behavior()
    {
        Console.WriteLine("........");
        return true;
    }    

    //Some other method definition
    public bool intelligent_behaviour()
    {
        return false;
    }
}

You would cast to IIntelligence to get the method implementation you wanted.


I found out casting to interface useful when developing plugins for main application. I created three projects. First project 'connectorInterface' contains only one class definition which is inteface. Interface code:

public interface IConnectorDataReader
{
  int ColumnCount
  {
    get;
  }

  bool readNextRecord();

  string this[int i]
  {
    get;
  }

  void reset();
}

Second project 'dataSource1' (plugin for main application) implements IConnectorDataReader interface and also class that implements interface has some additional private methods. Third project 'main application' when using plugin 'dataSource1' uses this code to read data from plugin 'dataSource1':

  Assembly assembly = Assembly.LoadFile(path); // path to dll
  Type type = assembly.GetType("dataSource1.DataReader");
  object myInstance = Activator.CreateInstance(type);

  MethodInfo method = type.GetMethod("getConnectorDataReader");
  object data = method.Invoke(myInstance, null);

  IConnectorDataReader reader =(IConnectorDataReader)data;

  // method usage
  while (reader.readNextRecord() == true) ....

In my case casting is useful to read plugins data. I do not care how plugin is implemented as long as it implements common interface. All I care and use is common methods for reading data. I suppose interfaces are useful and also casting back to interfaces.

0

精彩评论

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