码迷,mamicode.com
首页 > Windows程序 > 详细

C#扩展方法实现

时间:2015-04-28 18:06:35      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

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();

        }
    }
}

 

C#扩展方法实现

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!