如何将委托添加到接口C#

我需要在class上有一些代表。

我想使用界面来“提醒”我设置这些代表。

如何?

我的课堂是这样的:

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 { // ????? } 

那些声明委托types 。 他们不属于一个界面。 虽然使用这些委托types的事件很好,

 public delegate void UpdateStatusEventHandler(string status); public delegate void StartedEventHandler(); public interface IMyInterface { event UpdateStatusEventHandler StatusUpdated; event StartedEventHandler Started; } 

实现不会(也不应该)重新声明委托types,不仅仅是重新声明接口中使用的任何其他types。

从.NET 3.5开始,您还可以使用System.Action委托,这将导致以下接口:

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

Jon Skeet的回答是对的,我只是想添加一个注释。

接口不是为了“提醒”你要做什么或者在你的课程中包含什么。 接口是抽象的手段,用于面向对象的编程和devise方法。 也许你根本不需要接口声明,除非你想在程序的其他地方看到一些具体的类实例(Abstraction)。

如果你想在你的项目中执行一些编码标准,你可能想尝试使用代码分析工具(如在Visual Studio中) – 它们允许扩展,你可以合并来添加你自己的代码分析规则。

使用代码分析,如果你“忘记”添加委托(尽pipe我没有看到忘记它的意思,就好像委托没有被使用,这是不需要的),你会得到一个警告/错误。

只需将该代理公开为属性

 public delegate void UpdateStatusEventHandler(string status); public delegate void StartedEventHandler(); public interface IMyInterface { UpdateStatusEventHandler StatusUpdated {get; set;} StartedEventHandler Started {get; set;} } 

您的一个评论引用了事件处理程序的返回types。 你更关心处理程序的types,还是从事件返回的数据? 如果是后者,那么这可能会有所帮助。 如果没有,那么这个解决scheme是不够的,但可能会帮助你更接近你正在寻找的东西。

你所要做的就是将你的事件处理程序声明为接口和实现中的通用事件处理程序,你可以自定义返回结果。

你的conrete类看起来像这样:

 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(); } 

你的界面如下所示:

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

既然事件参数正在返回您的types,您可以将它们挂在您定义的任何处理程序中。

供参考: https : //msdn.microsoft.com/en-us/library/edzehd2t(v=vs.110).aspx

在派生类中inheritance的接口将提醒您定义并链接您在其中声明的内容。

但是你可能也想明确地使用它,你仍然需要把它和一个对象关联起来。

例如使用反转控制模式:

 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})"; } } 

你可以尝试这样的事情。

 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); } }