2013-07-16 20 views
0

我想以編程方式調用帶有事件的函數。字符串到事件

如何將字符串轉換爲一般事件?我的問題其實不知道如何做到這一點?

如何將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); 
+2

我們不知道什麼'UserControlsBackgroundEventArgs'是,這使得它很難幫助你...你的問題目前非常不清楚。請閱讀http://tinyurl.com/so-list(你甚至沒有試圖將字符串轉換爲*事件* - 你試圖將它轉換爲你的'UserControlsBackgroundEventArgs'類的一個實例,它不是' t事件... –

+0

現在我所能說的就是'UserControlsBackgroundEventArgs'應該具有保存'str'值的屬性。你能給你的問題添加更多的上下文嗎?什麼是真實世界的用法? – Leri

+0

「UserControlsBackgroundEventArgs = EventArgs」是什麼意思?它是同一個類嗎? – pascalhein

回答

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

你的事件類需要有一個構造函數接受一個字符串。然後,您將能夠使用字符串創建新的事件實例。您不能將字符串「轉換」爲事件類的實例。如果事件類來自庫或sth並且沒有字符串構造函數,那麼可以對它進行子類化,實現一個字符串構造函數並覆蓋輸出屬性。

0

如果你想這種轉換成爲可能,你必須使用一個explicit operator

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

這是唯一可能與一個新的類,不與EventArgs,因爲你不能更改代碼該類別。