如何将任何可以显示文本的对象传递给 C# 方法 [英] How to pass any object that can display text to a C# method

查看:52
本文介绍了如何将任何可以显示文本的对象传递给 C# 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个类的方法,该方法应该获取一个对象(例如文本框或标签)作为参数,并且每当需要向用户显示消息时,它都会使用该对象来显示消息.

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.

考虑以下方法:

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?

推荐答案

我会采用不同的方法.我将使用委托传递文本,而不是传入文本接收对象:

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

然后可以使用 lambda 表达式调用它:

This can then be called with a lambda expression:

TcpEndPoint(someIp, t => yourTextBox.Text = t);

这篇关于如何将任何可以显示文本的对象传递给 C# 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆