如何在C#中显示字符串消息 [英] How to display a string message in c#

查看:152
本文介绍了如何在C#中显示字符串消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

infomessage.Text += item.Tostring();
infoMessage.Text += pair.Key;



这两个代码处于两种不同的方法(函数)中.这些代码将消息以大字符串形式显示在Web上.由于它们具有不同的功能,所以我什至不能一起喜欢以下内容.



These two codes are in a two different methods ( functions). these codes display the messages together as a big string on the web.I can''t even do like the following together because they are in the different functions.

infoMessage.Text = string.Format("{0}\r\n{1}", pair.Key, item.ToString());



所以我尝试通过保持它们的方法来进行以下操作.



so I tried the following by keeping them in their method.

infoMessage.Text = string.Format("{0}",item.Tostring());// a string list
infoMessage.Text = string.Format("{1}",pair.Key          // a dictionary list



这次我只得到了item.Tostring()的显示,而下一个却没有.

我的目标是通过在两者之间留出一定的空间来展示它们.



this time i only get the item.Tostring() displaed but the next one dissapeard.

My objective is to show them both by having a space in between. Ho do I do it.

推荐答案

不清楚您的意思是这些代码采用两种不同的方法:"在您的示例中:"item"和"pair"(无论它们是什么)看起来好像它们在某个类中处于相同作用域中.

以上KairuByte的答案确实指出了在使用字符串连接时需要注意的事项.

如果您需要调用两种不同的方法来获取需要连接在一起以产生所需字符串结果的数据,则可以考虑编写类似
Not clear what you mean by "these codes are in two different methods:" in your example: both ''item'' and ''pair'' (whatever they are) appear as if they are in the same scope in some class.

The answer by KairuByte above does point out what you need to be aware of in using string concatenation.

If you need to call two different methods to get the data you need to join together to produce the desired string result, you might consider writing a function something like
public string BuildInfoMessage()
{
  return Class1Instance.SomeObject.Item.ToString() +  
  Class2Instance.SomeObject.Pair.ToString();
}

的函数.以上假设您可以从调用此函数的地方访问有效实例Class1和Class2,并且访问"Item"和"Pair"的那些类中的对象有效.

The above assumes you have access from where this function is called to valid instances of Class1, and Class2, and that the Objects in those classes in which you access ''Item'' and ''Pair'' are valid.


无需查看其余代码,最好的建议是这样做:

Without looking at the rest of your code, best suggestion would be to do:

infoMessage.Text = string.Format("{0}",item.Tostring());// a string list
infoMessage.Text += string.Format("{0}",pair.Key);               // a dictionary list



注意 second 字符串上的+ =.它必须在第一个值之后,否则您将覆盖infoMessage.Text中的当前值,而+ =会追加.

并且确保不要忘记第二个分号.

同样,您需要确保使用正确的参数标识符.第二次是对String.Format的另一次调用,该调用将重置参数标识符.



Note the += on the second string. It has to be after the initial one or you are just overwriting the current value in infoMessage.Text, while += appends.

And make sure to not forget the semicolon on the second one.

As well, you need to make sure to use the proper parameter identifier. The second time it is a different call to String.Format, which resets the parameter identifiers.


这篇关于如何在C#中显示字符串消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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