variable.ToString()与Convert.ToString(变量) [英] variable.ToString() vs. Convert.ToString(variable)

查看:240
本文介绍了variable.ToString()与Convert.ToString(变量)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有一个整数,我需要转换为字符串(我可能会用一个文本框的方式来显示的值给用户,例如。

Let's say I have an integer that I need to convert to a string (I might be displaying the value to the user by means of a TextBox, for example.

我应该preFER 的ToString() Convert.ToString()。他们都做同样的事情(是吗?)。

Should I prefer .ToString() or Convert.ToString(). They both do the same thing (don't they?).

int someValue = 4;

// You can do this
txtSomeValue.Text = someValue.ToString();

// Or this...
txtSomeValue.Text = Convert.ToString(someValue);

假设有两个之间没有运行差异,那么我的理由归结为美学和一致性。最近我一直在偏袒 Convert.ToString()因为对我来说,说:哎,我要的的这个东西作为一个字符串。不过,我知道,这并不完全正确......

Assuming that there is no runtime difference between the two, then my reasons come down to aesthetics and consistency. Recently I have been favouring Convert.ToString() as to me it says "hey, I want the value of this thing as a string". However I know that this is not strictly true...

推荐答案

一个测试

//This will set the variable test to null:
string test = Convert.ToString(ConfigurationSettings.AppSettings["Missing.Value"]);

//This will throw an exception:
string test = ConfigurationSettings.AppSettings["Missing.Value"].ToString();

得到 HTTP上现成的例子://博客。 asp.net/jgalloway/archive/2003/11/06/36308.aspx

您可以在这两者之间找到一些基准 http://blogs.msdn.com/brada/archive/2005 /03/10/392332.aspx

You can find some benchmarks between the two at http://blogs.msdn.com/brada/archive/2005/03/10/392332.aspx

所以,这取决于你preFER和你的风格是什么。

So, it depends what you prefer and what your style is.

这篇关于variable.ToString()与Convert.ToString(变量)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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