Inheritance 2 —– C # high-level programming (Sixth Edition)
(2010-09-09 16:25:55)

September 9, 2010
4.4 Interface
As mentioned earlier, if a class derived from an interface, it will perform certain functions. Not all languages ??support object-oriented interface, so this section will detail the C # interface.
Note: Developers familiar with COM should be noted that, while conceptually similar to C # interface to the COM interface, but they are different, the underlying structure is different, for example, C # interface is not derived from IUnknown. C # interface based. NET function provides a contract. With different COM interface, C # interface to represent any type of binary standard. Here are a pre-defined interface to Microsoft System.IDisposable complete definition. IDisposable contains a method Dispose (), the method of execution by the class for the clean-up code:
above code shows the interface declaration in the abstract class declaration syntax is identical with, but not to provide interfaces Any member of the execution. Under normal circumstances, the interface can only contain methods, properties, indexers, and events of the statement.
can not instantiate interface, it can only contain the signatures of its members. Interfaces can not have constructors (how to build an instance of the object can not be?) Or field (because it implies some internal implementation). Includes interface definition does not allow operator overloading, but not because of statements they have any problem in principle, but because the interface is usually a public contract, including operator overloading will cause some of the other. NET languages ??are not compatible with the problem, such as with VB is not compatible, because VB does not support operator overloading. In the interface definition statement also does not allow members of the modifier. Interface members are always public and can not be declared as virtual or static. If necessary, should be performed on the class declaration, it is best to declare the class through the implementation of access modifiers, like the above code does. For example, IDisposable. If you want to declare a public class type, in order to perform method Dispose (), the class must implement IDisposable. In C #, which means that the class derives from IDisposable.
In this example, if SomeClass derives from IDisposable, but the signature does not contain the same with the IDisposable Dispose () implementation code, you will get a compiler error because the class implements IDisposable contract destroyed . Of course, the compiler does not allow a class derived from IDisposable Dispose () method. The problem is not identified SomeClass other code support IDisposable features.
Note: IDisposable is a very simple interface, it only defines one method. Most of the interface contains many members. Another example is the interface in C # foreach loop. In fact, foreach loop is the inner workings of the query object to see if it implements System.Collections.IEnumerable interface. If it is, C # compiler into the IL code, the use of iterative methods on this interface, a member of the collection, otherwise, foreach will throw an exception. Chapter 10 will detail the IEnumerable interface. It should be noted, IEnumerable and IDisposable in a way the interface is a bit special, because they can be identified by the C # compiler, the C # compiler generated code will consider them. Obviously, their definition of the interface do not have this privilege.
4.4.1 define and implement interfaces
following the development of a standardized interface inheritance to follow a small example to illustrate how to define and use interfaces. This example based on the bank account basis. Assume that writing code and eventually allow computers to transfer between bank accounts business. Many companies can bank accounts, but they are each other bank accounts agree that all classes implement interfaces IBankAccount. The interface contains a method for the deposit and return the balance of a property. This interface also allows external code to identify the various different bank accounts, bank accounts executive class. Our aim is to communicate with each other to allow a bank account to transfer funds between accounts business, but has not introduced this feature. To keep the example simple, we put all the code examples are in the same source file, but in fact different types of bank accounts will be compiled into different assemblies, and these assemblies are located on different machines of different banks. However, those contents here for example is too complicated. In order to retain a certain authenticity, we define different companies for different namespaces.
First, the need to define IBank Interface:
Note that the interface name is IBankAccount. Traditionally, the interface names begin with the letter I to know that this is an interface.
Note: Chapter 2, in most cases,. NET usage rules do not encourage the use of so-called Hungarian notation, in the name preceded by a letter, that the type of object, interface Hungarian notation is recommended one of several names. Now you can write that type of bank account. These classes are not related to each other, they can be completely different class. But they have all bank accounts, because they have achieved IBankAccount interface.
Here is the first class, a run by the Royal Bank of Venus deposit account:
namespace Wrox.ProCSharp.VenusBank
{
public class SaverAccount: IBankAccount
{
private decimal balance;
public void PayIn (decimal amount)

{
balance = amount;
}
public bool Withdraw (decimal amount)

{
if (balance> = amount)
{
balance -= amount;
return true;
}
Console.WriteLine (“Withdrawal attempt failed.”);
return false;
} < br />
public decimal Balance
{
get
{
return balance;
}
}
public override string ToString ()
{
return String. Format (“Venus Bank Saver: Balance = {0,6: C}”,
balance);
}
}

}
implementation of this class the role of the code clear. Which contains a private field balance, when deposits or withdrawals on the adjustment of the field. If the amount in the account because of insufficient withdrawal fails, an error message. Also note that because we make the code as simple as possible, it does not implement additional attributes, such account holder name. In real life, this is the most basic information, but in this case, it is unnecessary. In this code, the only interesting class declaration:
SaverAccount derived from an interface IbankAccount, we did not specify any other base class (of course this means SaverAccount directly derived from System.Object) . In addition, derived from the interface is completely independent from the derived class. SaverAccount derived from IBankAccount, said it received a IBankAccount all members, but the interface does not actually implement its methods, so SaverAccount must provide all of these methods to achieve code. If no implementation code, the compiler will generate an error. Interface, only that the existence of its members, class members are responsible for determining the virtual or abstract (but only in the class itself is abstract, these members can be abstract). In this case, the interface method is not virtual. To illustrate how the different classes implement the same interface, the following assumption Planetary Bank of Jupiter is also the realization of a class GoldAccount to represent their bank account:
not listed here GoldAccount class details, because in this case It basically the same code with SaverAccount implementation.
GoldAccount and VenusAccount does not matter, they just happen to implement the same interface only.
have their own class, you can test them up. First need some using statements:
namespace Wrox.ProCSharp
{
class MainEntryPoint
{
static void Main ()
{
IBankAccount venusAccount = new SaverAccount ();
IBankAccount jupiterAccount = new GoldAccount ();
venusAccount.PayIn (200);
venusAccount.Withdraw (100);
Console.WriteLine (venusAccount.ToString ()); < br />
jupiterAccount.PayIn (500);
jupiterAccount.Withdraw (600);
jupiterAccount.Withdraw (100);
Console.WriteLine (jupiterAccount.ToString ());
}
}
}
In this section of code, a reference point is the reference variable is declared as IBankAccount way. This means that they can point to any class that implements the interface instance. But we can only call methods of the interface of these references – if you want to call the class implementation, not interface methods, you need to cast to the appropriate reference type. In this code, we call the ToString () (help IBankAccount to achieve), but without any explicit conversion, this is only because the ToString () method is a System.Object, C # compiler knows any classes support this method ( In other words, from the interface to the System.Object data type conversion is implicit). Chapter 6 describes the syntax of the cast. Interface reference can be seen as a class reference – but the interface reference to the powerful is that it can refer to any class that implements this interface. For example, we can construct an array of interfaces, which are different for each element of the class:
However, note that if you write the following code will generate a compile error:

4.4.2-derived interface
interface can inherit each other, the same way as class inheritance. Below by defining a new interface ITransferBank Account to illustrate this concept, the interface functions and IBankAccount the same, but they define a method, the funds directly to another account.
because ITransferBankAccount derived from IBankAccount, therefore, have IBankAccount and all members of its own members. This means that the implementation of (derived) ITransferBankAccount any class must implement all methods and IBankAccount defined in ITransferBankAccount new method TransferTo (). Did not perform all of these methods will produce a compiler error. Note, TransferTo () method used for the target account IBankAccount interface reference. This shows that the interface uses: in the implementation and call this method, you do not know the transfer of the object type, just know that the object can perform IBankAccount. The following shows ITransferBankAccount: assume Planetary Bank of Jupiter also provides a current account. CurrentAccount class most of the execution code execution with SaverAccount and GoldAccount the same code (which is only to make the example easier, is generally not the case), so in the following code, we only highlight a different place: < br />
public class CurrentAccount: ITransferBankAccount
{
private decimal balance;
public void PayIn (decimal amount)
{
balance = amount;
}
public bool Withdraw (decimal amount)
{
if (balance> = amount)
{
balance -= amount;
return true ;
}
Console.WriteLine (“Withdrawal attempt failed.”);
return false;
}
public decimal Balance
{
get
{
return balance; < br />
}
}
public bool TransferTo (IBankAccount destination, decimal amount)
{
bool result;
if ((result = Withdraw (amount)) == true)
destination.PayIn (amount);
return result;
}
public override string ToString ()
{
return String.Format (“Jupiter Bank Current Account: Balance =
{0,6: C} “,
balance);
}

}
static void Main ()
{
IBankAccount venusAccount = new SaverAccount ();
ITransferBankAccount jupiterAccount = new CurrentAccount ();
venusAccount.PayIn (200);
108 / 826
jupiterAccount.PayIn (500);

jupiterAccount.TransferTo (venusAccount, 100);
Console.WriteLine (venusAccount.ToString ());
Console.WriteLine (jupiterAccount.ToString () );
}
4.5 Summary
This chapter describes how to inheritance in C #. C # supports single implementation inheritance and multiple interface inheritance, but also provides a number of effective language
law structure to make the code more robust, such as the override keyword when it indicates that the function should override a base class function, new keywords shown in Table
function when the function to hide the base class, the constructor initializer of the hard and fast rules to ensure that the constructor to robust way to interact

operation.

Posted: January 3rd, 2012
at 2:23pm by admin

Tagged with


Categories: Uncategorized

Comments: No comments