关于c# 默认参数

#是不支持 默认参数的,今天在网上找了点资料,现在整理了;

模拟默认参数 :

源地址:http://msdn.microsoft.com/zh-cn/7s3cbse0(VS.80).aspx

class  MyClass
{
    
static   string  myMethod( string  precip,  string  country,  string  location)
    {
        
return   string .Format( " The {0} in {1} stays mainly in the {2}. " ,
            precip, country, location );
    }

    
static   string  myMethod( string  precip,  string  country )
    {
        
return  myMethod(precip, country,  " plain " );
    }

    
static   string  myMethod()
    {
        
return  myMethod( " rain " " Spain " " plain " );
    }
 
    
static   void  Main( string [] args)
    {
        System.Console.WriteLine(myMethod());
        System.Console.WriteLine(myMethod(
" snow " " Walla Walla " ));
    }
}

 

C#: 方法的默认参数

源地址:http://www.cnblogs.com/hush/articles/4355.html

 

 

大家都知道在C ++ 中,我们可以为方法的参数指定一个默认值,像这样:

void  foo( int  i  =   100 );

当我们以这种形式调用方法的时候: foo(); 实际上参数i被赋于了默认值,所以相当于调用了foo(
100 );
然而在C#中是不支持参数的默认值的,那么如果我们要用到类似的功能应该怎么实现呢?考虑下面这个例子:

class  Buffer
{
      
public  Buffer( int  bufferSize  =   100 // Compile Error
     {
            buf 
=   new   int  [bufferSize];
      }
      
private   int [] buf;
}


首先当然要为Buffer提供一个无参的构造函数重载:
class  Buffer
{
 
      
public  Buffer( int  bufferSize)
     {
            buf 
=   new   int [bufferSize];
     }
      
public  Buffer(): this ( 100 )
     {
      }
      
private   int [] buf;
}    

但这个方法有一个问题就是我们把Buffer的默认大小hard
- coding到了代码里,这有两个弊端,一是损害了代码的可读性,二是用以上方法,如果Buffer有多个重载的构造函数都用到bufferSize的默认值,一旦你要修改默认值的大小,不得不同时修改多处程序,一旦漏掉了其中的一个,说不定就麻烦大了。

所以,正确的方法是为bufferSize提供一个const的默认值:
class  Buffer
{
      
private   const   int  defaultBufferSize  =   100 ;
      
public  Buffer( int  bufferSize)
     {
            buf 
=   new   int [bufferSize];
      }
      
public  Buffer(): this (defaultBufferSize)
     {
     }
      
private   int [] buf;
}

观察编译器为public Buffer()产生的il代码

.method 
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即为defaultBufferSize的值
  IL_0009:  newarr     [mscorlib]System.Int32
  IL_000e:  stfld      int32[] Buffer::buf
  IL_0013:  ret
//  end of method Buffer::.ctor

defaultBufferSize的值在相应的调用处被替换成了字面常量(这其实也就是const成员的特性),所以使用defaultBufferSize不会影响public Buffer()的执行效率。而由于const成员隐含了static的特性,所以一个Buffer类只有一个defaultBufferSize的变量,性能的影响也是很小的。

我们可以看到.net 类库中的许多类都使用了这种方法 

 

做个收藏!

转载于:https://www.cnblogs.com/jevan/archive/2009/02/25/Jevan.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值