一周学会C#(函数三)

一周学会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型参数

}

refout修饰符可以是一个函数的标识。但是你不能同时重载refout型参数。refout修饰符在某种意义上是“安全的“,因为只有ref型实参才能传递给ref型函数参数,只有out型实参才能传递给out型函数参数。但是,当调用函数的时候,你会非常容易忘记refout修饰符,所以最好不要重载refout型参数。例如:

              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个函数的错误是:refout型参数只能用于函数参数和实参。

C#中可以通过函数重载的办法实现缺省参数的功能,以下是实现的方法:

              sealed class Overload

       {

              void DefaultArgument() { DefaultArgument(0.0); }

              void DefaultArgument(double d) { ... }

       }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章