C# 当对象确实是字符串时,将对象转换为字符串与将对象转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1170756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Casting vs Converting an object toString, when object really is a string
提问by David Bo?jak
This isn't really an issue, however I am curious. When I save a string in lets say an DataRow, it is cast to Object. When I want to use it, I have to cast it ToString. As far as I know there are several ways of doing this, first is
这不是一个真正的问题,但我很好奇。当我将一个字符串保存在一个 DataRow 中时,它会被转换为 Object。当我想使用它时,我必须将它转换为 ToString。据我所知,有几种方法可以做到这一点,首先是
string name = (string)DataRowObject["name"]; //valid since I know it's a string
and another one is:
另一个是:
string name = DataRowObject["name"].ToString();
I am interested in what is the difference between both? Is the first more efficient? (This is just a speculation, in my head ToString() method is implemented by some looping mechanism where just casting it "could" be faster, however this is just a "gut feeling" I have).
我感兴趣的是两者之间的区别是什么?第一个更有效率吗?(这只是一个推测,在我的脑海中 ToString() 方法是由某种循环机制实现的,在这种机制中,只是将其“可能”更快地进行转换,但这只是我的“直觉”)。
Is there even a faster / more elegant way of doing this?
有没有更快/更优雅的方式来做到这一点?
Can anyone clear this up for me?
谁能帮我解决这个问题?
采纳答案by Adriaan Stander
The two are intended for different purposes. The ToString method of any object is supposed to return a string representation of that object. Casting is quite different, and the 'as' key word performs a conditional cast, as has been said. The 'as' key word basically says "get me a reference of this type to that object if that object is this type" while ToString says "get me a string representation of that object". The result may be the same in some cases but the two should never be considered interchangeable because, as I said, they exist for different purposes. If your intention is to cast then you should always use a cast, NOT ToString.
两者用于不同的目的。任何对象的 ToString 方法都应该返回该对象的字符串表示形式。强制转换是完全不同的,正如前面所说,'as' 关键字执行有条件的强制转换。'as' 关键字基本上是说“如果该对象是这种类型,则为我获取该对象的此类型的引用”,而 ToString 则表示“为我获取该对象的字符串表示形式”。在某些情况下,结果可能相同,但绝不应将两者视为可互换的,因为正如我所说,它们存在的目的不同。如果您的意图是强制转换,那么您应该始终使用强制转换,而不是 ToString。
from http://www.codeguru.com/forum/showthread.php?t=443873
来自http://www.codeguru.com/forum/showthread.php?t=443873
see also http://bytes.com/groups/net-c/225365-tostring-string-cast
回答by Andrew Hare
If you know it is a String
then by all means cast it to a String
. Casting your object is going to be faster than calling a virtual method.
如果你知道它是 aString
那么一定要把它转换成 a String
。投射你的对象会比调用虚方法更快。
Edit:Here are the results of some benchmarking:
编辑:以下是一些基准测试的结果:
============ Casting vs. virtual method ============
cast 29.884 1.00
tos 33.734 1.13
I used Jon Skeet's BenchmarkHelper
like this:
我BenchmarkHelper
像这样使用 Jon Skeet :
using System;
using BenchmarkHelper;
class Program
{
static void Main()
{
Object input = "Foo";
String output = "Foo";
var results
= TestSuite.Create("Casting vs. virtual method", input, output)
.Add(cast)
.Add(tos)
.RunTests()
.ScaleByBest(ScalingMode.VaryDuration);
results.Display(ResultColumns.NameAndDuration | ResultColumns.Score,
results.FindBest());
}
static String cast(Object o)
{
return (String)o;
}
static String tos(Object o)
{
return o.ToString();
}
}
So it appears that casting is in fact slightlyfaster than calling ToString()
.
所以看来铸造其实稍微比调用快ToString()
。
回答by Dzmitry Huba
Basically in your case it is better to leave type cast because .ToString() may hide bugs. For example, your data base schema changed and name is no longer of string type but with .ToString() your code still works. So in this case it is better to use type cast.
基本上在您的情况下,最好保留类型转换,因为 .ToString() 可能会隐藏错误。例如,您的数据库架构已更改,名称不再是字符串类型,但使用 .ToString() 您的代码仍然有效。所以在这种情况下最好使用类型转换。
Here is implementation of String.ToString() - nothing special =)
这是 String.ToString() 的实现 - 没什么特别的 =)
public override string ToString()
{
return this;
}
回答by Anton Gogolev
Downcasting is a relatively slow operation since CLR has to perform various runtime type-checks. However, in this particular scenario casting to string
is more appropriate than calling ToString()
for the sake of consistency (you can't call ToInt32
on object
, but cast it to int
) and maintanability.
向下转换是一个相对较慢的操作,因为 CLR 必须执行各种运行时类型检查。然而,在此特定情形铸造string
比调用更合适ToString()
的一致性的缘故(你不能叫ToInt32
上object
,而是投它int
)和maintanability。
回答by dfa
In this case:
在这种情况下:
string name = DataRowObject["name"].ToString();
since it is a string
, I think that the ToString()
method of a string object is simple as:
既然是string
,我认为ToString()
字符串对象的方法很简单:
return this;
so IMHO there is no performance penalty.
所以恕我直言,没有性能损失。
PS I'm a Java programmer, so this anwser is only a guess.
PS 我是一名 Java 程序员,所以这个 anwser 只是一个猜测。
回答by martijn_himself
ToString() does not perform a cast by default. Its purpose is to return a string that represents the type (e.g. "System.Object").
ToString() 默认不执行强制转换。它的目的是返回一个表示类型的字符串(例如“System.Object”)。
If you want to avoid casting you could try to think of an implementation that is strongly typed (using generics, for example) and avoids DataRowObject altogether.
如果您想避免强制转换,您可以尝试考虑一种强类型(例如使用泛型)并完全避免 DataRowObject 的实现。
回答by Soul_Master
For data object, I suggest you to use "as" keyword like the following code.
对于数据对象,我建议您像下面的代码一样使用“as”关键字。
string name = DataRowObject["name"] as string;
Please check it before you use value.
请在使用 value 之前检查它。
if(name != null)
{
// statement for empty string or it has value
}
else
{
// statement for no data in this object.
}
回答by Soul_Master
I want to make one more comment
我想再发表一条评论
If you are going to use casting: string name = (string)DataRowObject["name"] you will get an Exception: Unable to cast object of type 'System.DBNull' to type'System.String' in case if the record in the database table has null value.
如果您打算使用强制转换: string name = (string)DataRowObject["name"] 您将得到一个异常:如果记录在数据库表有空值。
In this scenario you have to use: string name = DataRowObject["name"].ToString() or
在这种情况下,您必须使用: string name = DataRowObject["name"].ToString() 或
You have to check for null value like
你必须检查空值,如
if(!string.IsNullOrEmpty(DataRowObject["name"].ToString()))
{
string name = (string)DataRowObject["name"];
}
else
{
//i.e Write error to the log file
string error = "The database table has a null value";
}
回答by n00b
I know you mentioned that the Object is a string, but incase you're afraid that the returned object is null, you can also cast using "Convert.ToString(DataRowObject["name"]);" This has the added benefit of returning an empty string (string.empty) if the object is null, to avoid any null reference exceptions (unless of course you want an exception thrown in such cases).
我知道你提到对象是一个字符串,但如果你担心返回的对象是空的,你也可以使用“Convert.ToString(DataRowObject["name"]);” 如果对象为空,这具有返回空字符串 (string.empty) 的额外好处,以避免任何空引用异常(当然,除非您希望在这种情况下抛出异常)。