c# 随机数使用及有返回值方法return的使用

class MainClass
{
public static void Main (string[] args)
{
//-----Random(随机数)类的使用--------
Random r = new Random();
//next方法  得到一个随机数,该方法有返回值
//(10,100)是取值区间 
int num = r.Next(10,100);
//此处打印下num
Console.WriteLine (num);


//有返回值的方法
Person p = new Person();
//当一个方法有返回值时要接收,接收时的类型取决于定义时的类型
//此处可以这样写   int x = new Person();
int x = p.GetNum();
//定义a和b的值
int s = p.Sum (1, 2);
//打印该值	此处是拼字符串 结果是 d 25 如果去掉"d="会只剩数值
Console.WriteLine ("s="+s);
//定义a和b值
int d = p.Sum(12,13);
//打印该值	此处是拼字符串 结果是 d 25 如果去掉"d="会只剩数值
Console.WriteLine ("d="+d);


Dog v = p.Test ();
Console.WriteLine (v);
}
}
//此处定义有返回值的方法
class Person{
//此处定义一个返回值为int类型的Sum
public int Sum(int a , int b)
{
//有返回值类型的方法必须添加关键字 return
return a + b;
}
//有返回值类型的方法必须添加关键字 return
public int GetNum()
{
//return返回结束方法后在return之后的代码是不被执行的
return 10;	
}
//返回值类型 可以是任意类型 1.void   
//2.值类型(当为值类型 必须返回值类型)   
//3.引用类型(当为引用类型时 传递的值为该类的对象)


//此处定义一个Dog返回类型
public Dog Test(){
//返回是Dog类型的对象
Dog d = new Dog();
//有返回值类型的方法必须添加关键字 return
return d;
//此处可以这样写 return new Dog();
}
}
class Dog
{


}
}

猜你喜欢

转载自blog.csdn.net/qq_39609115/article/details/81003321