C #: The default parameters of the method (Justin Shen)

xiaoxiao2021-03-06  74

Everyone knows in C , we can specify a default value for the parameters of the method, like this:

Void foo (int i = 100);

When we call the method in this form: foo (); actually parameter i is assigned the default, it is equivalent to calling Foo (100);

However, in C # is the default value of the parameters, then what should we implement if we want to use a similar function? Consider the following example:

Class buffer

{

Public buffer

Int buffersize = 100)

// compile error

{

BUF =

New int [buffersize];

}

PRIVATE INT [] BUF;

}

First of all, it is of course necessary to provide a non-arranging-free constructor overload for Buffer:

Class buffer

{

Public buffer

Int buffersize

{

BUF =

New int [buffersize];

}

Public buffer ():

THIS (100)

{

}

PRIVATE INT [] BUF;

}

But this method has a question is that we have the default size hard-code in the buffer to the code, which has two drawbacks, one is to impair the readability of the code, and the other is used by the above method, if buffer has multiple overloaded The constructor uses the default value of buffersize. Once you want to modify the default size, you have to modify multiple programs, once you miss one of them, maybe you are buddy.

Therefore, the correct way is to provide a Const default value for buffersize:

Class buffer

{

Private const Int defaultBuffersize = 100;

Public buffer

Int buffersize

{

BUF =

New int [buffersize];

}

Public buffer ():

this (defaultbuffersize)

{

}

PRIVATE INT [] BUF;

}

Observing the IL code generated by the compiler for public buffer ()

Public Hidebysig SpecialName RTSpecialName

Instance void .ctor () CIL Managed

{

// Code Size 20 (0x14)

.maxstack 2

IL_0000: ldarg.0

IL_0001: Call Instance Void [Mscorlib] System.Object ::. Ctor ()

IL_0006: ldarg.0

IL_0007: ldc.i4.s 100 // 100 is the value of defaultBuffersize

IL_0009: NEWARR [mscorlib] system.int32

IL_000E: Stfld Int32 [] Buffer :: buf

IL_0013: RET

} // end of method buffer ::. ctor

The value of defaultBuffersize is replaced by a literal constant at the corresponding call (this is actually the characteristics of the Const member), so using defaultBuffersize does not affect the execution efficiency of public buffer (). Since the Const member implies Static's characteristics, a Buffer class has only a variable of defaultBuffersize, and the performance of performance is also small.

We can see that many classes in the .Net class library use this method.

Posted on 2004-03-27 12:44 Justin Shen

转载请注明原文地址:https://www.9cbs.com/read-120905.html

New Post(0)