The following small series brings you a method of instantiating an interface object in C #. Small series feel very good, now share to everyone, also for everyone to make a reference. Let's take a look at it with a little knitting.
A lot of interface objects were used in head first design mode
The first thing to clarify is that the interface can not only declare objects, but also instantiate objects, and can be passed as parameters.
One, interface callback
This is the upward transformation in succession. The parent class fl=new (), except that the parent class here is the interface interface. (Personally, this is the same usage, whether it's a class override or a interface rewrite)
You can assign a reference to an object created by an interface class to an interface variable declared by that interface variable, which can invoke methods in an interface that is implemented by the class. In fact, when an interface variable calls a method in an interface that is implemented by a class, it notifies the corresponding object to invoke the interface method
Directly on the code
Using system;using system.collections.generic;using system.linq;using system.text;namespace ConsoleApplication1{ Interface Itemp { double plus (); } public class Num:itemp { double aa, BB; Public num (double A, double b) { this.bb = b; This.aa = A; } public double Plus () { return (AA * BB); } } Class program { static void Main (string[] args) { num n = null;//declares class object reference Itemp TM = null;// Declares the interface object reference TM = new NUM (1.1, 2.2);//interface callback (upward transition) Console.WriteLine (Tm.plus ()); Console.readkey ();}}}
From the above example, it is not difficult to see that the instantiation of an interface object is actually an interface object as a reference to all methods in the class that implements its method, much like a function pointer in C + + (similar to a delegate in C #), but there is a difference. The interface object instantiation in C # is actually a one-to-many, and the function pointers in C + + are one-to-one.
However, it is important to note that the instantiation of an interface object must be instantiated with the class that implements it, not by the interface itself. Instantiating its own object with the interface itself is not allowed in C #.