EventArgs需要将对象的参数传递给事件处理程序。但我不想传递论据。如何删除class C : EventArgs {}
?
using System;
class D
{
public event EventHandler eventEH;
public void someMethod(C e) // class C are used here, that's why I can't to remove it
{
EventHandler objEH = eventEH;
if (objEH != null)
objEH(this, e);
}
}
class C : EventArgs {} // Need to remove
class B
{
public B(D objD)
{ objD.eventEH += new EventHandler(display); }
void display(object sender, EventArgs e)
{ Console.WriteLine("display"); }
}
class A
{
static int Main()
{
D objD = new D();
B objB = new B(objD);
C objC = new C();
objD.someMethod(objC);
return 0;
}
}
答案 0 :(得分:1)
EventHandler委托看起来像:
void EventHandler(object, EventArgs);
但是,事件可以在您想要的任何代理上。
如果你真的想要" C"在您的事件中,只需将事件声明为:
public event Action<C> EventEH.
否则你可以使用Action
。然后你可以删除继承等。此时你也不需要EventHandler对象,只需给出函数名称就可以了。您的最终代码如下:
using System;
class D
{
public event Action<C> eventEH;
public void someMethod(C e)
{
EventHandler objEH = eventEH;
if (objEH != null)
objEH(e);
}
}
class C {}
class B
{
public B(D objD)
{ objD.eventEH += display; }
void display(C cObject)
{ Console.WriteLine("display"); }
}
class A
{
static int Main()
{
D objD = new D();
B objB = new B(objD);
C objC = new C();
objD.someMethod(objC);
return 0;
}
}
或者,没有&#34; C&#34;:
using System;
class D
{
public event Action eventEH;
public void someMethod()
{
EventHandler objEH = eventEH;
if (objEH != null)
objEH();
}
}
class B
{
public B(D objD)
{ objD.eventEH += display; }
void display()
{ Console.WriteLine("display"); }
}
class A
{
static int Main()
{
D objD = new D();
B objB = new B(objD);
objD.someMethod();
return 0;
}
}