C#依頼デモ
同様に分離方法【声明】と【実現】に用いることができる.
依頼をいつ使うか、インタフェースをいつ使うかは、まだ分からない問題です.
依頼が便利で、インタフェースが面倒な場合があるかもしれません.
たとえば、同じクラスでは、メソッドの複数のバージョンを実装する必要があります.
この場合、依頼が複数のインタフェースを容易に実現できる同じ方法で、依頼呼び出しに送る.インタフェースがちょっと不便です.
以下に簡単なプレゼンテーション用ウィンドウプログラムを作成します.
ウィンドウプログラムを作成し、ボタンをクリックすると上のエラーハンドラClass 1を呼び出す
依頼をいつ使うか、インタフェースをいつ使うかは、まだ分からない問題です.
依頼が便利で、インタフェースが面倒な場合があるかもしれません.
たとえば、同じクラスでは、メソッドの複数のバージョンを実装する必要があります.
この場合、依頼が複数のインタフェースを容易に実現できる同じ方法で、依頼呼び出しに送る.インタフェースがちょっと不便です.
以下に簡単なプレゼンテーション用ウィンドウプログラムを作成します.
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);
}
}
}
ウィンドウプログラムを作成し、ボタンをクリックすると上のエラーハンドラClass 1を呼び出す
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);
}
}
}
}