C#扩展方法实现

C#扩展方法的实现,可用于通过定义接口方法,实现多类继承。

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

namespace ConsoleApplication12
{
    //定义接口
    public interface IEntity
    {
        string ID { set; get; }
        string Name { set; get; }
    }
    //实现扩展方法
    public static class IEntityExtentMethod
    {
        public static string getName(this IEntity obj)
        {
            return obj.ID +":"+ obj.Name;
        }
    }
    //实现接口类
    public class DemoEntity : IEntity
    {
        public string ID { set; get; }
        public string Name { set; get; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            //定义对象,并赋值
            DemoEntity de = new DemoEntity();
            de.ID = "001";
            de.Name = "Test";

            //使用扩展方法
            string rlt = de.getName();

            Console.WriteLine(rlt);
            Console.Read();

        }
    }
}
原文地址:https://www.cnblogs.com/jerron/p/4463393.html