事件的字符串

本文关键字:字符串 事件 | 更新日期: 2023-09-27 18:22:49

我正在尝试以编程方式调用带有事件的函数。

一般来说,如何将字符串转换为事件?我的问题实际上是不知道该怎么做?

如何将str转换为event?

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

事件的字符串

我写了一个模仿你代码的代码,希望你会发现它很有用:

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

您的事件类需要有一个接受字符串的构造函数。然后,您将能够使用字符串创建一个新的事件实例。不能将字符串"转换"为事件类的实例。如果事件类来自库或sth,并且没有字符串构造函数,则可以将其子类化,实现字符串构造函数并重写输出属性。

如果你想实现这种转换,你必须使用explicit operator:

public static explicit operator UserControlsBackgroundEventArgs(string s)
{
    var args = new UserControlsBackgroundEventArgs();
    args.output = s;
    return args;
}

这只适用于新类,而不适用于EventArgs,因为您无法更改该类的代码。

您的UserControlsBackgroundEventArgs实现可以提供隐式/显式强制转换。

看看隐式关键字文档

然而,沃伊切赫·布德尼亚克的答案更好。