---
title: "C#委托演示"
author: "yutianc"
date: "2010-06-20T16:15:11Z"
tags: []
categories: ["编程语言"]
slug: "c"
draft: false
lastmod: "2010-06-20T18:09:11Z"
id: 695083
url: "https://yutianc.iteye.com/blog/695083"
---

同样都能用来分离方法【声明】和【实现】
何时用委托，何时用接口，这是个暂时还没搞明白的问题。

可能有一些情况用委托方便,而用接口则比较麻烦。
比如，在同一个类中，需要实现方法的多个版本。
这时候，用委托可以方便的实现多个接口相同的方法，送给委托调用；而接口就有点不方便了。

下面做了一个简单的演示用窗口程序。

```C#

using System;
using System.Collections.Generic;
using System.Text;

namespace myFormApp.lib
{
    class Class1
    {
        //委托声明
        public delegate void outputMsg(string message);

        public void dealWithError(String strMsg,outputMsg inDel)
        {
            /*
             *TODO 错误处理逻辑是演示用的控制台打印
             */
            System.Console.WriteLine("dealwith error!");

            //用传递进来的错误信息打印方法答应信息。
            //但是此处不意识具体的信息输出方式。
            inDel(strMsg);
        }
    }
}

```


做一个窗口程序，点击按钮时调用上面的错误处理程序Class1

```C#

using System;
using System.Text;
using System.Windows.Forms;
using myFormApp.lib;
using System.IO;

namespace myFormApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //按钮点击触发
        private void button1_Click(object sender, EventArgs e)
        {
            Class1 testObj = new Class1();

          //调用错误处理方法，同时传入putMsgToConsole方法的地址，将信息出到控制台
            testObj.dealWithError("errorMsg to console!", putMsgToConsole);

            //调用错误处理方法，同时传入putMsgToFile方法的地址，将信信息出到文件
            testObj.dealWithError("errorMsg to File!", putMsgToFile);

        }


        //委托的实现方法1，将信息出于控制台
        private void putMsgToConsole(String msg)
        {
            System.Console.WriteLine(msg);
        }

        //委托的实现方法2，将信息出于文件
        private void putMsgToFile(String msg)
        {
            string path = @"D:\TestMsg.log";

           if (!File.Exists(path))
            {
                using (FileStream fs = File.Create(path)) { }
            }

            using (FileStream fs = File.OpenWrite(path))
            {
                Byte[] info =
                    new UTF8Encoding(true).GetBytes(msg);
                fs.Write(info, 0, info.Length);
            }
        }
    }
}

```