Archive for the ‘idisposable’ tag

[Reserved] C # keywords – using

November 18, 2011
using keyword has two main purposes:
(a ) as instructions for creating an alias for a namespace or import other types defined in a namespace.
(b) As a statement, used to define a range, in this range will be released at the end of the object.
using directive
① allow the use of types in a namespace, so you do not have space in the name of a limited a type of use:
using System.Text;
using PC.Company;
< br /> ② To create an alias for a namespace or type.
using MyCompany = PC.Company; / / namespace alias.
using Project = PC.Company.Project; / / type of alias
using namespace introduced, does not mean that the compiler compiled with the set the namespace where the assembly, assembly process of the load depends on the existence of an assembly operation is invoked , if there is no code, the compiler will call the action does not load using the namespace where the introduction of the assembly. Therefore, beginning in the source file, the introduction of multiple namespaces, not loading multiple assemblies, will not cause “excessive reference” of the state.
create an alias for another important reason is that the same file into a different namespace includes the type of the same name, such as SharpMap.Geometries.Point with System.Drawing.Point. To avoid name conflicts can be resolved by setting an alias:
using SGPoint = SharpMap.Geometries.Point;
using SDPoint = System.Drawing.Point;
Although we can type the whole name to be distinguished, but this is clearly not the best solution. Create an alias with the using directive, effective solution to this potential naming conflicts, is the best solution.
using statement
using statement allows the programmer to specify the use of resources when the object should release resources. objects used in a using statement must implement the IDisposable interface. This interface provides the Dispose method, which will release resources for this object.
① being declared in the using statement object.
Font font2 = new Font (“Arial”, 10.0f);
using (font2)
{

/ / use font2
}
② in the using statement before the statement object.
using (Font font2 = new Font (“Arial”, 10.0f))
{
/ / use font2 < br />
}
③ Multiple objects can be used together with the using statement, but must be declared inside the using statement in these objects.
using (Font font3 = new Font (“Arial”, 10.0f), font4 = new Font (“Arial”, 10.0f))
{
/ / Use font3 and font4.
}
use rules
① using can only be used to implement the IDisposable interface type, to prohibit the type does not support the IDisposable interface using statement, otherwise it will appear compile error ;
using statement for clean-up individual unmanaged resources, and more to clean up the unmanaged object is best to try-finnaly to achieve, because there may be nested using statement to hide the Bug. inner using block throws an exception, will not block the release of the outer layer of the object using resources;
③ using multiple variable initialization statement to support, but only the type of these variables must be the same For example:
using (Pen p1 = new Pen (Brushes.Black), p2 = new Pen (Brushes.Blue))
{

/ /
}
④ for the initialization of the different types of variables can be declared as IDisposable type are, for example:
using (IDisposable font = new Font (“Verdana”, 12), pen = new Pen (Brushes.Black))
{
float size = (font as Font) . Size;
Brush brush = (pen as Pen). Brush;
}
using real
at the assembly stage, the compiler will automatically be using try-finally statement is generated as a statement in the finally block and call the object Dispose method to clean up resources. Therefore, using try-finally statement is equivalent to the statement, for example:
Font f2 = new Font (“Arial”, 10, FontStyle.Bold);
try
{
/ / perform text drawing operations
}
finally
{
if (f2! = null) ((IDisposable) f2). Dispose ();
}

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

Tagged with


Categories: Uncategorized

Comments: No comments


Implements IDisposable in order to achieve a more elegant code

October 30, 2010
know from msdn, using statement is used to call the object Dispose method:
As a rule, when using IDisposable objects should be in the using statement declare and instantiate the object. using statement in the correct way to call the Dispose method on the object, and (as shown in the previous way you use it) will result in the call Dispose the object is outside the scope of their own. In the using block, the object is read-only and can not be modified or re-allocation.
ran into such a situation: by implementing the IDisposable interface Wrapper: The code then becomes: It seems it is more elegant. When you need more processing time, only changes to the wrapper, without the need to make any changes to the calling code, flexibility is better.
Note: This article has nothing to do with IDisposable to release resources.

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

Tagged with


Categories: Uncategorized

Comments: No comments


Implement the IDisposable interface standard

December 3, 2010
The main purpose of this interface is to release unmanaged resources. When not using managed objects, the garbage collector automatically releases the memory allocated to the object. But can not predict when garbage collection
room. In addition, the garbage collector handle of the window or open the file and know nothing about unmanaged resources such as streams.
this interface, the Dispose method used in conjunction with the garbage collector explicitly release unmanaged resources. When no longer needed object, the object the user can call this method.
the following to achieve a standard IDisposable interface: public class MyClass: IDisposable {private bool _Disposed = false; public void Dispose () {Dispose (true); GC.SuppressFinalize (this);} ~ MyClass ( ) {Dispose (false);} private void Dispose (bool disposing) {if (! this._Disposed) {if (disposing) {/ / release resources} _Disposed = true;}}}

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

Tagged with


Categories: Uncategorized

Comments: No comments


. Net Detailed garbage collection mechanism

November 6, 2011
http://www.cnblogs.com/tianzhiliang/archive/2011/0 3/06/1972604.html1. Automatic memory management and GC
in the original program heap memory allocation is this: find the first to have enough memory address space (not occupied), then the memory allocation. When the program no longer needs this information in memory when programmers need to manually release this memory. Heap memory is common, meaning that all processes are likely to cover the contents of the memory of another process, which is why a lot of poorly designed program or operating system itself will fall down. We sometimes encounter unexplained dead program (random phenomena), but also because of improper memory management (possibly because of their program or external program memory problems caused). Another common example is that we often see the game Trainer, their memory by directly modifying the game to “Invincible” effect. Understand that we can imagine that if the memory address of these were confused with how dangerous it would be, we can also imagine why C programmers (some of) the mention of the pointer on the causes of headache. In addition, if program memory is not the case then the programmer to manually release the memory will not be re-allocated until the computer re-starting up, what we call a memory leak. These are referred to in unmanaged code, CLR AppDomain to achieve through the isolation between the code to avoid these memory management problems, that under normal circumstances one AppDomain can not read / write memory to another AppDomain. Managed memory is released on the GC (Garbage Collector) to be responsible. We want to further talk about is the GC, but before that first talk about the allocation of memory in managed code, the managed heap memory allocation is sequential, meaning that the allocation of a next one. This memory allocation is higher than, the original program, but the speed will be higher than the GC looking back. Why? After reading the GC work you will know the answer.
2. GC work
First, we need to know what the objects in managed code, when we recall to mind (unless GC.Collect to force GC collection, this is not recommended, will explain why later). GC will be in its “happy” when the implementation of a recovery (for many reasons, such as the memory is not enough time. This is done to improve memory allocation, collection efficiency). So if we use the Destructor it? Did not work, because. NET in the Destructor of the concept does not exist, it becomes a Finalizer, which will be shown later. Remember that an object is present only in the absence of any reference to circumstances that can be recycled. To illustrate this point consider the following piece of code:
objectobjA = newobject ();
objectobjB = objA;
objA = null; < br />
/ / to force recovery.
GC.Collect ();
objB.ToString ();
here objA referenced object has not been recovered, because the object also There is another reference, ObjB. In the absence of any reference to the object to be recovered after the conditional.
When the GC recovery, it will do the following steps:
1, to determine the object does not have any references.
2, check whether the object is recorded on the table in the Finalizer. If there are records in the Finalizer table, then moved to another record on a table, where we call it Finalizer2. If you do not Finalizer2 record on the table, then release the memory. In Finalizer2 Finalizer objects on the table will be a low priority in another thread on the execution removed from the table. When the object is created, the GC will check whether the object has Finalizer, if there will be added to the table records in the Finalizer. We are talking about here is actually the record pointer. If you look closely these steps, we will find a Finalizer object for the first time will not be recovered, that is, there is more than one Finalizer object to the Collect operation will be recycled, so we should slow step, so the authors recommended unless it is absolutely necessary not to create a Finalizer.
GC in order to improve the efficiency of the use of recycled Generation of the concepts, principles, this is the first object is created before the recovery of Generation 0, after the recovery time when the number will be back this Generation Norwegian one, that is, the second recycling into the original Generation 0 Generation 1, but recovered in the first and second objects created before recovery will belong to Generation 0. GC will first try to belong to Generation 0 objects in the collection, because these are the latest, the most likely to be recycled, such as some function of local variables in the exit function is not quoted (which can be recycled). If the Generation 0 recovered enough memory, then the GC will not be followed by recovery, if recovery is not enough, then the GC will try to recover in the Generation 1, if it is not recovered in the Generation 2, this and so on. Generation also has a maximum limit, according to the Framework version, you can use GC.MaxGeneration available. In the recovery of memory after GC will reschedule the entire memory, so there is no space between the data, this is because the CLR in order to allocate memory, it can not free the memory between the memory. Now we know that each time a certain recovery time will be wasted CPU time, this is what I say in general do not manually GC.Collect reasons.
When we Destructor syntax, the compiler will automatically write it as a protected virtual void Finalize (), this method is what I call the Finalizer. As the name says, it used to end certain things, not to destroy (Destruct) things. In Visual Basic, it is the Finalize method of the form, so Visual Basic programmers do not have to worry about. C # programmers use statistics Destructor syntax to write Finalizer, but do not confused,. NET has no Destructor up. C , we can accurately know when it will perform Destructor, but in. NET, we can not know when it will implement Finalizer, because it is the first object in the recovery operation after the implementation. We can not know that Finalizer execution order, that is the same case, A Finalize may be executed first, B after the execution, execution may be A and B after the first run. In other words, the code in the Finalizer, we can not have any time logic. Here we calculate the number of instances of a class as an example, that the different Destructor and Finalizer and Finalizer in that time in a logical error:
publicclassCountObject {
publicstaticintCount = 0;
publicCountObject () {
Count ;
}
~ CountObject () {
Count -;
}}
staticvoidMain () {
CountObject obj;
for (inti = 0; i <5; i ) {
obj = null; / / This step is redundant, so just to write some more clearly!
obj = newCountObject ();
}
/ / Count will be 1, because the Finalizer will not immediately be triggered until there is a recovery operation will be triggered.
Console.WriteLine (CountObject.Count);
Console.ReadLine ();
}
Note that the above If the switch to C code to write, then memory leaks will occur, because we do not use the delete operator to manually clean up the memory, but not in managed code is a memory leak, because the GC does not automatically detect and recover the object references. Here the author recommended that you implement the IDisposable interface only when used in conjunction with Finalizer, in other cases do not use (there may be special circumstances).
3. the object of the resurrection
what? Recovery of the object can also be “resurrected” it? Yes, although the definition is not accurate to say. Let look at some code:
publicclassResurrection {
publicintData;
publicResurrection (intdata) {
this . Data = data;
}
~ Resurrection () {
Main.Instance = this;
} }
publicclassMain {
publicstaticResurrection Instance;
publicstaticvoidMain () {
Instance = newResurrection (1); < br />
Instance = null;
GC.Collect ();
GC.WaitForPendingFinalizers ();
/ / to see to do, where “resurrection”.
Console.WriteLine (Instance.Data);
Instance = null;
GC.Collect ();

Console.ReadLine ();
}}
You may ask: “If this object can be resurrected, then this object in the program will be recycled after the end of it?” . Will be, “Why?.” Let us take the work in accordance with GC once you understand how the matter.
1, perform Collect. Check the references. No problem, the object has no references.
2, create a new instance of the table has been made in the Finalizer record, so we checked into the object has Finalizer.
3, as found in the Finalizer, so the record moves Finalizer2 table.
4, in Finalizer2 table record, so I do not release memory.
5, Collect is finished. Then we use the GC.WaitForPendingFinalizers, so we will wait on the table Finalizers all Finalizer2 implementation.
6, Finalizer execution of our Instance on another reference to our object. (Resurrected)
7, once again to remove all references.
8, perform Collect. Check the references. No problem.
9, has since the last record deleted from the Finalizer table, so this is not found objects Finalizer.
10, in Finalizer2 table does not exist, so the object memory is released.
release unmanaged resources until now, we say that the managed memory management, so when we use such as databases, files and other unmanaged resources it? At this time we have to use the. NET Framework Standard: IDisposable interface. As standard, all you need to manually release the unmanaged resource class had to implement this interface. The interface has one method, Dispose (), but there are relatively Guidelines indicate how to implement this interface, and here I talk to you. This class implements the IDisposable interface, the need for such a structure:
publicclassBase: IDisposable {
publicvoidDispose () {
this.Dispose (true) ;
GC.SupressFinalize (this);
}
protectedvirtualvoidDispose (booldisposing) {
if (disposing) {
/ / managed class
}
/ / release unmanaged resources
}
< br /> ~ Base () {
this.Dispose (false);
}}
publicclassDerive: Base {
< br /> protectedoverridevoidDispose (booldisposing) {
if (disposing) {
/ / managed class
}
/ / release unmanaged resources
base.Dispose (disposing);
}}
Why this design? Let me explain what followed. Now we talk about the Dispose method to achieve this several criteria: it does not throw any errors, repeat the call can not throw an error. That is, if I have an object called Dispose, Dispose is called when my second time the program should not be wrong, simply call Dispose in the second program will not do anything. These can determine if a flag or multiple realization. Dispose of an object to achieve the release of all the resources of this object. Take for example a derived class, derived class uses unmanaged resources, so it implements the IDisposable interface, if the class inherits the base class also uses unmanaged resources, the base class have to be released, how the resources of the base class in the derived class release it? Of course, is a virtual / Overridable methods, and so we are able to guarantee that each call to Dispose. This is why we have designed a virtual / Overridable Dispose method. Note that we first have to release the resource class inherit the base class and then release the resources. Because unmanaged resources must protect the right to be free so we have to define a Finalizer to avoid programmers forget to call Dispose of the situation. The above design on the use of this form. If we manually call the Dispose method is not necessary to retain Finalizer, so we used in the Dispose GC.SupressFinalize remove the object from the Finalizer table, so that when the recycling rate will be faster. So that disposing and “managed class” is how it happened? Is this: in the “managed class” write all you want to call Dispose can be released so they are in the state of managed code. Remember we said that we do not know when to release the managed code is it? Here we just get rid of members of the object reference it can be recycled in the state, not directly to free memory. In the “managed class” in here, we write all the members of the object implements IDisposable, because they also have a Dispose, so it needs to call the object Dispose their Dispose, so as to ensure that the second criterion. disposing to distinguish call the Dispose method, if we call it manually to the second criterion, “managed class” part of the course was implemented, but if it is Finalizer calls Dispose, this time the object has no references, that is a member of an object not exist naturally (no reference), there is no need to implement “managed class” section, because they can be recycled in the state. Well, this is all the IDisposable interface. Now let us recall the past, we may think that memory will soon have a Dispose released, this is wrong. Only unmanaged memory will be immediately released, the release managed memory managed by the GC, we do not control.
4. weak references use
A = B, we call such a reference is called a strong reference, GC is a strong reference to the decision by checking whether an object can be recycled . There is also a reference called weak references (WeakReference), this reference does not affect the GC recovery, this is where it useful. You may ask what is the use in the end. Now let assume we have a fat object, which means it takes up a lot of memory. We used this object, it intends to remove the reference to memory so GC can be recycled, but much effort we need this object, and no way to re-create the instance, how to create such a Mana? Is there any way to solve this problem? There, the objects behind in memory not to fast it! But we do not want too fat to total occupied memory object, and we do not want to always create a new instance of this fat because this is very time consuming. How to do that …? Smart friends must have guessed I would say that solution is a weak reference. Yes, that it. We can create a weak reference object of this fat, so that GC can be recycled when the memory is not enough, does not affect the memory usage, and in the GC has not been recovered before we can re-use of the object. Here an example:
publicclassFat {
publicintData;
publicFat (intdata) {
this.Data = data;
}}
publicclassMain {
publicstaticvoidMain () {
Fat oFat = newFat (1);
WeakReference oFatRef = newWeakReference (oFat);
/ / From here, Fat object can be recovered.
oFat = null;
if (oFatRef.IsAlive) {
Console.WriteLine (((Fat) oFatRef.Target). Data) ; / / 1
}
/ / mandatory recycling.
GC.Collect ();
Console.WriteLine (oFatRef.IsAlive); / / False
Console.ReadLine ();
}}
Fat is not really where our fat, but can reflect the intention of examples: How to use weak references. Finalizer that if Fat has it, what will happen? Fat Finalizer if we could have used another WeakReference constructor, which has a parameter called TrackResurrection, if it is True, as long as the Fat of the memory is released we can not use it, that Fat After we perform the Finalizer can be restored Fat (equivalent to the first recovery operation can resume Fat); if TrackResurrection is False, then the recovery operation after the first object of the Fat can not be restored.
5. Summary
I am here to write a positive article main points:
an object only when there is no reference in the case of will be recycled.
an object memory is not released immediately, GC will be recovered at any time. Generally do not enforce recycling.
If there is no special need not write Finalizer.
Finalizer do not have time to write some logic in the code.
in any unmanaged resources Dispose of or containing members of the class implement the IDisposable interface.
Dispose in accordance with the design given in the Dispose write their own code.
When fat can be considered weak object references to use.

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

Tagged with


Categories: Uncategorized

Comments: No comments


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