Programing

인터페이스 C #에 대리자를 추가하는 방법

lottogame 2020. 10. 5. 07:27
반응형

인터페이스 C #에 대리자를 추가하는 방법


수업에 대표자가 필요합니다.

인터페이스를 사용하여 이러한 델리게이트를 설정하도록 "알리게"하고 싶습니다.

어떻게?

내 수업은 다음과 같습니다.

public class ClsPictures : myInterface
{
    // Implementing the IProcess interface
    public event UpdateStatusEventHandler UpdateStatusText;
    public delegate void UpdateStatusEventHandler(string Status);

    public event StartedEventHandler Started;
    public delegate void StartedEventHandler();
}

해당 대리자를 강제하는 인터페이스가 필요합니다.

public interface myInterface
{
   // ?????
}

그것들은 대리자 유형을 선언하고 있습니다 . 그들은 인터페이스에 속하지 않습니다. 이러한 대리자 유형을 사용 하는 이벤트 는 인터페이스에있는 것이 좋습니다.

public delegate void UpdateStatusEventHandler(string status);
public delegate void StartedEventHandler();

public interface IMyInterface
{       
    event UpdateStatusEventHandler StatusUpdated;    
    event StartedEventHandler Started;
}

구현은 인터페이스에서 사용되는 다른 유형을 재 선언하는 것보다 더 많이 대리자 유형을 재 선언하지 않습니다 (그리고 그렇게해서는 안됩니다).


.NET 3.5부터 System.Action 대리자를 사용할 수도 있습니다. 그러면 다음 인터페이스가 생성됩니다.

public class ClsPictures : myInterface
{       
   // Implementing the IProcess interface
   public event Action<String> UpdateStatusText;

   public event Action Started;
}

대리자를 속성으로 노출하기 만하면됩니다.

public delegate void UpdateStatusEventHandler(string status);
public delegate void StartedEventHandler();

public interface IMyInterface
{       
    UpdateStatusEventHandler StatusUpdated {get; set;}    
    StartedEventHandler Started {get; set;}
}

Jon Skeet의 대답이 맞습니다. 메모를 추가하고 싶습니다.

수행 할 작업 또는 클래스에 포함 할 내용을 "알려주는"인터페이스가 없습니다. 인터페이스는 객체 지향 프로그래밍 및 디자인 방법에 사용되는 추상화 수단입니다. 프로그램의 다른 곳에서 인터페이스로 구체적인 클래스 인스턴스를보고 싶지 않다면 (추상화) 인터페이스 선언이 전혀 필요하지 않을 수도 있습니다.

프로젝트에서 일부 코딩 표준을 적용하려는 경우 코드 분석 도구 (예 : Visual Studio)를 사용해 볼 수 있습니다. 확장을 허용하여 사용자 고유의 코드 분석 규칙을 추가 할 수 있습니다.

코드 분석을 사용하여 대리자를 추가하는 것을 "잊으면"(대리자가 사용되지 않는 것처럼 잊어 버리는 지점은 알 수 없지만 필요하지 않음) 경고 / 오류가 발생합니다.


One of your comments referenced the return type of event handler. Are you more concerned with the type of the handler, or the data coming back from the event? If it's the latter, then this may help. If not, then this solution won't be enough, but may help get you closer to what you're looking for.

All you have to do is declare your event handlers as generic event handlers in both the interface and your implementation and you can customize the return results.

Your conrete class would look like this:

public class ClsPictures : myInterface
{
    // Implementing the IProcess interface
    public event EventHandler<UpdateStatusEventArgs> UpdateStatusText;
    //no need for this anymore: public delegate void UpdateStatusEventHandler(string Status);

    public event EventHandler<StartedEventArgs> Started;
    //no need for this anymore: public delegate void StartedEventHandler();
}

Your interface would look like this:

public interface myInterface
{
   event EventHandler<StartedEventArgs> Started;
   event EventHandler<UpdateStatusEventArgs> UpdateStatusText;
}

Now that the event args are returning your types, you can hook them in any handler you define.

For reference: https://msdn.microsoft.com/en-us/library/edzehd2t(v=vs.110).aspx


The interface inherited within your derived class will remind you to define and link up the stuff you declared in it.

But you may also want to use it explicitly and you will still need to associate it to an object.

For example using an Inversion of Control pattern:

class Form1 : Form, IForm {
   public Form1() {
     Controls.Add(new Foo(this));
   }

   // Required to be defined here.
   void IForm.Button_OnClick(object sender, EventArgs e) {
     ...
     // Cast qualifier expression to 'IForm' assuming you added a property for StatusBar.
     //((IForm) this).StatusBar.Text = $"Button clicked: ({e.RowIndex}, {e.SubItem}, {e.Model})";
   }
 }

You can try something like this.

interface IForm {
  void Button_OnClick(object sender, EventArgs e);
}


class Foo : UserControl {
  private Button btn = new Button();

  public Foo(IForm ctx) {
     btn.Name = "MyButton";
     btn.ButtonClick += ctx.Button_OnClick;
     Controls.Add(btn);
  }
}

참고URL : https://stackoverflow.com/questions/3948721/how-to-add-a-delegate-to-an-interface-c-sharp

반응형