C# 面向對象 方法的調用


C# 面向對象 方法的調用

1、方法可以傳值類型,引用類型、傳可變參數

2、用ref和out將傳值類型改為傳引用類型。

例1:ref舉例

class Program

{

static void Print(ref int i)

{

i = 10;

}

static void Main(string[] args)

{

int i = 0;

Print(ref i);

Console.WriteLine(i);

}

}

輸出結果:10;

例2:out舉例

class Program

{

static void Print(out int i)

{

i = 10;

}

static void Main(string[] args)

{

int i;

Print(out i);

Console.WriteLine(i);

}

}

輸出結果:10;

Out和ref的區別:

1、使用ref參數時,傳入的參數必須首先被初始化,out不需要,但必須在方法中完成初始化。

2、使用out和ref時,在方法的參數和執行方法時,都要加上ref和out關鍵字,以滿足匹配。

3、out使用在需要return多個返回值的地方,而ref則用在需要被調用的方法修改調用者的引用的時候。方法參數上的out方法參數關鍵字引用傳遞到方法的同一變量。當控制傳遞迴調方法時,在方法中對參數所做的任何更改都將反應在該變量中。

例:傳引用舉例

public class Student

{

public int Age { get; set; }

}

class Program

{

static void Print(Student s)

{

s.Age = 10;

}

static void Main(string[] args)

{

Student st = new Student();

st.Age = 0;

Print(st);

Console.WriteLine(st.Age);

}

}

輸出結果:10

注:此種寫法依然是傳值,結果為0

class Program

{

static void Print(int i)

{

i = 10;

}

static void Main(string[] args)

{

Student st = new Student();

st.Age = 0;

Print(st.Age); Console.WriteLine(st.Age);

}

}

在方法形參前加上params就是可變參

傳可變參數舉例:

class Program

{

static void Print(params int[] s)

{

s[0] = 10;

}

static void Main(string[] args)

{

Print(1, 2, 3, 4);

}

}

注:當有多個參數時,parames只能修飾最後一個參數,例:static void Print(int[] arr,parames string s)

注:如果方法參數是接口,那麼調用該方法的時候,參數可以是實現該接口的任意對象。

如果方法作為接口的返回類型,方法可以返回實現該接口的類的對象。

例:

namespace JieKou

{

public interface IFly

{

void Fly();

}

public class Bird : IFly

{

#region IFly 成員

public void Fly()

{

Console.WriteLine("Bird.IFly");

}

#endregion

}

public class Plane : IFly

{

#region IFly 成員

public void Fly()

{

Console.WriteLine("Plane.IFly");

}

#endregion

}

class Program

{

public static IFly Do()

{

return new Bird();

}

public static void Do(IFly ly)

{

ly.Fly();

}

static void Main(string[] args)

{

Bird b = new Bird();

Do(b);

Plane p = new Plane();

Do(p);

IFly ly = Do();

ly.Fly();

}

}

}


分享到:


相關文章: