一週學會C#(函數三)
C#才鳥(QQ:249178521)
8.ref/out重載<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
· ref / out 在大部分情況下是標識的一部分!
w 你可以重載一個ref型參數和一個普通參數
w 你可以重載一個out型參數和一個普通參數
w 你不可以重載一個ref型參數和一個out型參數
sealed class Overloading
{
void Allowed( int parameter)
{ ... }
void Allowed(ref int parameter)
{ ... }
//正確,重載一個ref型參數和一個普通參數
void AlsoAllowed( int parameter)
{ ... }
void AlsoAllowed(out int parameter)
{ ... }
//正確,重載一個out型參數和一個普通參數
void NotAllowed(ref int parameter)
{ ... }
void NotAllowed(out int parameter)
{ ... }
//錯誤,不能重載一個ref型參數和一個out型參數
}
ref和out修飾符可以是一個函數的標識。但是你不能同時重載ref和out型參數。ref和out修飾符在某種意義上是“安全的“,因爲只有ref型實參才能傳遞給ref型函數參數,只有out型實參才能傳遞給out型函數參數。但是,當調用函數的時候,你會非常容易忘記ref和out修飾符,所以最好不要重載ref和out型參數。例如:
sealed class Overloading
{
public static void Example(int parameter)
{ ... }
public static void Example(ref int parameter)
{ ... }
static void <?xml:namespace prefix = st1 ns = "urn:schemas-microsoft-com:office:smarttags" />Main()
{
int argument = 42;
Example(argument);//在這兒非常容易忘記ref修飾符
}
}
9.訪問規則
l 函數參數或返回值不能比所屬函數的訪問級別低
sealed class T { ... } //類的默認訪問級別是internal
public sealed class Bad
{
public void Parameter(T t) //錯誤,函數的訪問級別(public)比參數高
{ ... }
public T Return() //錯誤,函數的訪問級別(public)比返回值高
{ ... }
}
public sealed class Good
{
private void Parameter(T t) //正確,函數的訪問級別(private)比參數低
{ ... }
private T Return() //正確,函數的訪問級別(private)比返回值低
{ ... }
}
10.找錯誤
sealed class Buggy
{
void Defaulted(double d = 0.0) 1
{ ...
}
void ReadOnly(const ref Wibble w) 2
{ ...
}
ref int ReturnType() 3
{ ...
}
ref int fieldModifier; 4
}
第1個函數的錯誤是:C#中函數不能擁有缺省參數。
第2個函數的錯誤是:ref型參數不能用const修飾,因爲ref型參數是可能變化的。
第3,4個函數的錯誤是:ref和out型參數只能用於函數參數和實參。
C#中可以通過函數重載的辦法實現缺省參數的功能,以下是實現的方法:
sealed class Overload
{
void DefaultArgument() { DefaultArgument(0.0); }
void DefaultArgument(double d) { ... }
}