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();

}

}

}


分享到:


相關文章: