C# 学习笔记 13. 类的扩展方法

1.扩展方法

是一种方法,可以用来扩展已定义的类型中的方法成员。

1.扩展方法必须在非嵌套,非泛型静态类中定义。

2.它至少有一个参数;

3.第一个参数必须加上this 关键字作为前缀。

4.第一参数不能使用其它任何修饰符(ref,out 等)

5.第一个参数类型不能是指针类型。

//例子1 
namespace currentExtern
{
    using customerExtren;

    public class Person
    {
        public string name { get; set; }
    }

    public static class extrenTest1
    {
        public static void printname(this Person per)
        {
            Console.WriteLine("current extren!" + per.name);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Person p1 = new Person() { name = "hello" };
            p1.printname();
            p1.printname("1111");

            Console.WriteLine();
            Console.ReadKey();
        }
    }
}

namespace customerExtren
{
    using currentExtern;
    public static class extrenTest1
    {
        public static void printname(this Person per)
        {
            Console.WriteLine("cotomoer extren!" + per.name);
        }
        public static void printname(this Person per, string s)
        {
            Console.WriteLine("cotomoer extren!" + per.name + s);
        }
    }
}

2.空引用也可以调用扩展方法

1.不会报异常,具体原因后面再分析。

 

你可能感兴趣的:(1.c#_学习笔记,c#)