我正在尝试以编程方式调用带有事件的函数。
如何将字符串转换为一般事件?我的问题实际上是不知道如何做到这一点?
如何将str转换为事件?
str = "test1";
// UserControlsBackgroundEventArgs = EventArgs
EventArgs arg = (EventArgs)str; --> ?
UserControlsBackgroundOutput(str);
//function
private string CLICKNAME = "test0";
private void UserControlsBackgroundOutput(EventArgs e)
{
if (CLICKNAME == e.output)
return;
if (e.output == "test1"){}
}
错误已解决: 我不得不做
UserControlsBackgroundEventArgs arg = new UserControlsBackgroundEventArgs(CLICKNAME);
而不是
UserControlsBackgroundEventArgs arg = new (UserControlsBackgroundEventArgs)(CLICKNAME);
答案 0 :(得分:0)
您的事件类需要有一个接受字符串的构造函数。然后,您将能够使用字符串创建新的事件实例。您不能将字符串“转换”为事件类的实例。如果事件类来自库或sth并且没有字符串构造函数,则可以对其进行子类化,实现字符串构造函数并覆盖输出属性。
答案 1 :(得分:0)
您的UserControlsBackgroundEventArgs
实施可以提供隐式/显式转换。
查看implicit keyword documentation
然而,Wojciech Budniak的答案更好。
答案 2 :(得分:0)
如果您希望进行此类转换,则必须使用explicit operator
:
public static explicit operator UserControlsBackgroundEventArgs(string s)
{
var args = new UserControlsBackgroundEventArgs();
args.output = s;
return args;
}
这只适用于新课程,而不是EventArgs
,因为您无法更改该课程的代码。
答案 3 :(得分:0)
我已经编写了一个模仿代码的代码,希望你会发现它很有用:
public class UserControlsBackgroundEventArgs
{
public string output;
public UserControlsBackgroundEventArgs(string up)
{
output = up;
}
}
public delegate void UserControlsBackgroundOutputHandle(UserControlsBackgroundEventArgs e);
public class testEvent
{
public event UserControlsBackgroundOutputHandle UserControlsBackgroundOutput;
public void DoSomeThings()
{
// do some things
if (UserControlsBackgroundOutput != null)
{
string str = "test1";
UserControlsBackgroundEventArgs arg = new UserControlsBackgroundEventArgs(str);
UserControlsBackgroundOutput(arg); // you've done that with str, whitch makes me
// you don't know what the event param is
}
}
}
public class test
{
private testEvent myTest;
private const string CLICKNAME = "whatever"; // i don't know what you want here
public test()
{
myTest = new testEvent();
myTest.UserControlsBackgroundOutput += UserControlsBackgroundOutput;
}
void UserControlsBackgroundOutput(UserControlsBackgroundEventArgs e)
{
if (CLICKNAME == e.output)
return;
if (e.output == "test1")
{
}
}
}