C#类(16) 扩展方法

ExtensionProcedure.cs

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

//扩展方法的声明方式 :  修饰符 static 返回类型 方法名 (this 需要添加方法的类 参数名 , 参数列表)如下:


public static void Extension (this String s , string value)
namespace ConsoleApplication1 { public static class ExtensionProcedure // 扩展方法必须声明在静态类中 { //给String类添加一个方法. public static string ShowValue(this String y, string value) { return value; } //给下面那个MyClass类添加一个方法, public static int Age(this MyClass M, int value) { return value; } } public class MyClass { } }

           

 

 

Program.cs

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = null;
            str = str.ShowValue("Tony");
            Console.WriteLine(str);
           
            MyClass my = new MyClass();
            int age = my.Age(19);
            Console.WriteLine(age.ToString());

        }
    }
}
//扩展方法的特点


// 1. 扩展方法是给现有的类添加一个方法。
// 2. 扩展方法是通过指定关键字this修饰方法的第一个参数 , 且必须是静态方法。
// 3. 扩展方法必须声明在静态类中。
// 4. 扩展方法要通过对象来调用,虽然定义的时静态方法。
// 5.扩展方法可以带参数

 

 

 

posted @ 2012-10-29 22:04  梦断难寻  阅读(395)  评论(0编辑  收藏  举报