• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
冥海
博客园    首页    新随笔    联系   管理    订阅  订阅

委托与接口之我看

1.接口与委托都可以对方法进行调用,不同的是
接口是通过对实现接口类的里面的方法进行调用的,接口变量指向实现接口的类。
然后调用方法。
            List<int> list1 = new List<int>();
            list1.Add(10);
            list1.Add(5);
            list1.Add(-13);
            list1.Add(-7);
            list1.Add(2);

            Icomputer icom = new A();//接口指向实现接口的类
            foreach (int i in list1)
            {
                if (icom.oushu(i))
                {
                    Console.WriteLine(i);
                }
            }

interface Icomputer
{
    bool oushu(int i);
}

class A : Icomputer
{

        #region Icomputer 成员

        public bool oushu(int i)
        {
            return i % 2 == 0;
        }

        #endregion
}

而委托的话,不仅可以调用别的类里的方法,而且可以进行多方法调用,即一次可以调用多个方法。
static void Main(string[] args)
{
            List<int> list1 = new List<int>();
            list1.Add(10);
            list1.Add(5);
            list1.Add(-13);
            list1.Add(-7);
            list1.Add(2);

            Icomputer icom = new A();
            adelegate ade = new adelegate(new A().oushu) + new B().dayu;
            foreach (int i in list1)
            {
                if (ade(i))  //通过委托的方法进行调用
                if (icom.oushu(i)) //通过接口的方法进行调用
                {
                    Console.WriteLine(i);
                }
            }

            Console.ReadKey();
}

interface Icomputer //声明一个委托
{
        bool oushu(int i);
}

public class A : Icomputer
{

        #region Icomputer 成员

        public bool oushu(int i)
        {
            return i % 2 == 0;
        }

        #endregion

}

public class B
{
   public bool dayu(int i)
    {
      return i > 0;
    }
}
delegate bool adelegate(int i);

★★★★★委托可以调用实现接口的类的方法。

posted @ 2011-04-18 11:05  冥海  阅读(178)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3