问题
I'm trying to write a method of a class that should get an object (such as textbox or label) as a parameter and whenever it needs to show a message to the user it uses the object to show the message.
As the class will be used in other programs, it should be a little portable and it should implement the functioning to any text-based object such as labels or textboxs etc.
Consider the following method:
public void TcpEndPoint(string IP,/* a text-based object */)
{
// There's a need to show a message
// to the user by the text-based object
}
Is there any way to implement this, or is this kind of programming is not proper for portable classes?
回答1:
I would go for a different approach. Instead of passing in the text receiving object I would pass out the text using a delegate:
public void TcpEndPoint(string IP, Action<string> setText)
{
setText(message);
}
This can then be called with a lambda expression:
TcpEndPoint(someIp, t => yourTextBox.Text = t);
回答2:
The thing you call text-based object
is I assume Windows.Forms.Control. This class is the base class for all visual objects in windows forms. So you can use that class and get
it's Text
property.
public void TcpEndPoint(string IP, Control _object)
{
...
MessageBox.Show(_object.Text);/// or in any other way you like.
...
}
updated:
And if you want to set
the Text
property of the object and show the message on it, just use it like this:
public void TcpEndPoint(string IP, string message, Control _object)
{
...
_object.Text = message; /// or in any other way you like.
...
}
来源:https://stackoverflow.com/questions/28249286/how-to-pass-any-object-that-can-display-text-to-a-c-sharp-method