(6)C#方法,作用域,方法重载

1、方法

返回类型 方法名(参数列表)

例如:int a(int b,int c)

{

  方法体

  return b+c;

}

函数如果有返回类型则最后要用return一个和返回类型一样的数据。

 

2、无返回类型的方法

void 方法名(参数列表)

{

 

}

3、调用方法

调用1的例子

a(25,36);

 

4、作用域

 在方法中定义的变量只能在方法里使用,在类中定义的变量这整个类中都能使用(包括方法里)。

 在类中定义的变量通常叫做字段

 

5.扩展方法 --C#3.0

 

    class Program
    {
        static void Main(string[] args)
        {
            Student s = new Student();
            s.Score();
            s.Age(21);
        }
    }

    class Student 
    {
        public void Score() { Console.WriteLine("Score..."); }  
    }
    //扩展的类必须是静态的
    static class ExtendStudent
    {
        //扩展的方法必须为静态的,第一个参数格式为 this+需要扩展的类名+参数
        public static void Age(this Student s,int age) { Console.WriteLine("Age..."+age); }
    }

 扩展方法必须再作用域内,如果在令一个命名空间中,using +命名空间

 实例方法优先于级高于扩展方法

posted @ 2016-06-21 15:18  富坚老贼  阅读(339)  评论(0编辑  收藏  举报