Home » ASP.NET » Analysis of the importance of interface in C#

Analysis of the importance of interface in C#

C# has the concept of interfaces. I think interfaces are like abstract base classes in C++.

Interfaces can be understood as a convention that makes the classes or structures that implement this interface consistent in form,.


declaration interface:

Syntax is exactly the same as declared abstract class.


public interface IBankAccount
{
void PayIn (decimal amount);
bool Withdraw (decimal amount);
decimal Balance
{
get;
}
}

note: contains the method, only the interface property, indexer and event statement. It is not permitted to declare a member of the modifiers, even pubilc are not, because the interface members are always public, also can not be declared as virtual and static. If you need to make the best modifier implementation class to declare.


interface using:


class SaverAccount: IBankAccount
{
private decimal balance;
public decimal Balance
{
get
{
return balance;
}
}
public void PayIn (decimal amount)
{
Balance = amount;
}
public bool Withdraw (decimal amount)
{
if (balance = amount)
{
Balance = amount;
return true;
}
Console.WriteLine (, Withdraw, failed., );
return false;
}
public, override, string, ToString ()
{
return String.Format (, Venus, Bank, Saver:Balance={0,6:C}, , balance);
}
}

summary:

1, the interfaces in C# are defined independently of classes. This is antagonistic to the C++ model. In C++, the interface is really an abstract base class.

2, interfaces and classes can inherit multiple interfaces.

3, a class can inherit the base class interface, no class inheritance. This model avoids the problem of multiple inheritance of C++, C++ in different base in conflict may arise. Therefore no longer need to develop such as virtual inheritance and explicit type scope of this kind of complex mechanism of.C# simplifies the interface model to help speed up the application the
program.
4, an interface to define a reference only abstract members made a practical interface type in.C#, only there are ways to sign, but simply did not carry out the code. This implies that cannot instantiate an interface, can only instantiate a derived from the interface to
.
5, interfaces can define methods, properties, and indexes. So, comparing a class, the specificity of the interface is that when you define a class, you can derive from multiple interfaces, and you can only derive from only one class.

As we mentioned at the beginning of the C# in the interface as the abstract class C++ in C#, but also exist in the abstract class, the abstract class and interface in c# and what is the difference? Please look at the blog <
$(function () {
$('pre.prettyprint, Code').Each (function () {)
VaR, lines = $(this),.Text (),.Split ('n'),.Length;
VaR, $numbering = $('

Latest