幾個C#編程的小技巧 (二)

來源:互聯網
上載者:User
編程|技巧 一、判斷檔案或檔案夾是否存在
使用System.IO.File,要檢查一個檔案是否存在非常簡單:
bool exist = System.IO.File.Exists(fileName);

如果需要判斷目錄(檔案夾)是否存在,可以使用System.IO.Directory:
bool exist = System.IO.Directory.Exists(folderName);

二、使用delegate類型設計自訂事件
在C#編程中,除了Method和Property,任何Class都可以有自己的事件(Event)。定義和使用自訂事件的步驟如下:
(1)在Class之外定義一個delegate類型,用於確定事件程式的介面
(2)在Class內部,聲明一個public event變數,類型為上一步驟定義的delegate類型
(3)在某個Method或者Property內部某處,觸發事件
(4)Client程式中使用+=操作符指定事件處理常式


例子: // 定義Delegate類型,約束事件程式的參數
public delegate void MyEventHandler(object sender, long lineNumber) ;

public class DataImports
{
// 定義新事件NewLineRead
public event MyEventHandler NewLineRead ;

public void ImportData()
{
long i = 0 ; // 事件參數
while()
{
i++ ;
// 觸發事件
if( NewLineRead != null ) NewLineRead(this, i);
//...
}
//...
}
//...
}

// 以下為Client代碼

private void CallMethod()
{
// 聲明Class變數,不需要WithEvents
private DataImports _da = null;
// 指定事件處理常式
_da.NewLineRead += new MyEventHandler(this.DA_EnterNewLine) ;
// 調用Class方法,途中會觸發事件
_da.ImportData();
}
// 事件處理常式
private void DA_EnterNewLine(object sender, long lineNumber)
{
// ...
}


三、IP與主機名稱解析
使用System.Net可以實現與Ping命令列類似的IP解析功能,例如將主機名稱解析為IP或者反過來: private string GetHostNameByIP(string ipAddress)
{
IPHostEntry hostInfo = Dns.GetHostByAddress(ipAddress);
return hostInfo.HostName;
}
private string GetIPByHostName(string hostName)
{
System.Net.IPHostEntry hostInfo = Dns.GetHostByName(hostName);
return hostInfo.AddressList[0].ToString();
}







聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.