我需要这样做(使用自定义滑块或标准控件):
ISlider ISlider;
ISlider = slider as ISlider;
if (ISlider != null)
{
ISlider.CustomEvent += new CustomEventDelegate(MyCustomEventHandler);
}
else
{
// standard control
this.slider.ValueChanged += new RoutedPropertyChangedEventHandler<double>(this.slider_ValueChange);
}
但是C#拒绝了,因为它说接口不能包含字段(CustomEvent),如果我没有在接口中声明CustomEvent,我上面的代码也无法编译,那么我该怎么办?
在ISlider界面中,我只是试图声明:
CustomEventDelegate CustomEvent ;
答案 0 :(得分:9)
确实不应将CustomEvent声明为ISlider中的字段。它应该声明为事件:
public delegate void CustomEventDelegate(/*whatever*/);
public interface ISlider {
event CustomEventDelegate CustomEvent;
}
修复代码,使类型名和引用变量名不同:
ISlider itf;
itf = slider as ISlider;
if (itf != null)
{
itf.CustomEvent += new CustomEventDelegate(MyCustomEventHandler);
}