2014-05-15 3 views
0

다음 방법을 사용하여 FileSystemEventHandler를 설정하여 config.xml 파일의 변경 사항을 모니터링합니다.FileSystemEventHandler 메서드를 매개 변수로 사용

public void WatchConfigFile(???) 
{ 
    this.watcher = new FileSystemWatcher(); 
    DirectoryInfo _di = Directory.GetParent(configFile); 
    this.watcher.Path = _di.FullName; 
    this.watcher.Filter = Path.GetFileName(configFile); 
    this.watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.CreationTime; 
    this.watcher.Changed += new FileSystemEventHandler(???); 
    this.watcher.EnableRaisingEvents = true; 
    log.Info("Config watcher established at " + watcher.Path); 
} 

나는 우리가 반복해서 사용하지만 방법으로는 onChanged 방법 핸들러를 전달하고 감시자에 할당하는 방법을 모른다 표준 방법의 라이브러리에이 방법을 추가하고 싶습니다. ???로 표현되는 방법 이 같은 것 (변경 사항을 처리하기 위해) :

public void ConfigFileChanged(object source, FileSystemEventArgs e) 
{ 
    // Do something when file is updated 
} 

나는대로이를 호출 할 수 싶습니다 것은 다음과 그냥 같이 핸들러 자체를 원하는처럼

_library.WatchConfigFile(ConfgiFileChanged); 

답변

2

음 소리가 난다 매개 변수 :

public void WatchConfigFile(FileSystemEventHandler handler) 
{ 
    ... 
    this.watcher.Changed += handler; 
    ... 
} 

괜찮을 것입니다. WatchConfigFile으로 전화하면 ConfigFileChanged에서 FileSystemEventHandler으로 변환되는 방법 그룹이 있습니다.

는 는

(곰 염두에 현재 당신이 두 번 호출하는 경우, 당신은 더 이상 최초의 감시자에 대한 참조가되지 않도록 ... this.watcher의 현재 내용을 대체 WatchConfigFile 방법. 아마도 당신은 List<FileSystemWatcher> 원하는 그 대신)

+0

감사합니다! 나는 그것을 필요 이상으로 어렵게 만들고 있었다. 또한 List 와 같은 아이디어. – BrianKE

0

가능성은 delegates입니다.

  • 는 클래스의 필드로 핸들러 방법을 지정하거나 매개 변수로 사용하는 사용자 정의 위임
  • 을 입력하는 방법을
  • 이 클래스에 정의 대리자의 정의을 만들

대표 : 사용

public delegate void ConfigFileChangedHandler(object source, FileSystemEventArgs e); 

클래스 대리자는 다음과 같이 할 수 있습니다

public class Dummy 
{ 
    public ConfigFileChangedHandler FileChangedHandler { get; set; } 
    public void UseTheAction(ConfigFileChangedHandler action) 
    { 
     // invoke 
     action(this, null); 
     // or bind 
     // object.Event += action; 
    } 
} 

사용법 :

var dummy = new Dummy(); 
dummy.FileChangedHandler += ConfigFileChanged; 
dummy.UseTheAction(ConfigFileChanged); 

private void ConfigFileChanged(object source, FileSystemEventArgs e) 
{ 
    Console.WriteLine("Event fired"); 
} 
관련 문제