Access to a method's string from other method in C#
I have a method which name is:
public void OnPublic(UserInfo user, string channel, string message)
And the method which handles a button click:
private void 开发者_Python百科button1_Click(object sender, EventArgs e)
Now, how could I access the string channel
of the method OnPublic
on button1_Click
?
Thanks, I'm a beginner in C# :)
When your OnPublic
method is called you can store a reference to the string in a private field and then you can later access it from the other method in your class.
private string channel;
public void OnPublic(UserInfo user, string channel, string message)
{
this.channel = channel;
// etc...
}
private void button1_Click(object sender, EventArgs e)
{
// You can use this.channel here.
}
channel
is a parameter to the OnPublic
method, its value is only visible within OnPublic
when OnPublic
gets called. You could copy it to an instance variable _channel
though:
private string _channel;
public void OnPublic(UserInfo user, string channel, string message)
{
_channel = channel;
//..
}
You can now access the instance variable _channel
in your other method.
I'm not sure what you're doing with this, but you could also put the code for the button in the OnPublic method. And even if you want to wait for the user to click the button for the code to execute, it may be better if the user would click the button multiple times (so it doesn't have to process the info again).
精彩评论