개체가 실제로 문자열 일 때 개체를 문자열로 캐스팅 대 변환
이것은 실제로 문제가 아니지만 궁금합니다. 문자열을 저장하면 DataRow라고하면 Object로 캐스트됩니다. 사용하고 싶을 때는 ToString을 캐스팅해야합니다. 내가 아는 한 여러 가지 방법이 있습니다. 먼저
string name = (string)DataRowObject["name"]; //valid since I know it's a string
그리고 또 하나는 :
string name = DataRowObject["name"].ToString();
둘의 차이점에 관심이 있습니까? 첫 번째가 더 효율적입니까? (이것은 단지 추측 일뿐입니다. 내 머리에서 ToString () 메서드는 캐스팅하는 것이 더 빠를 수있는 루핑 메커니즘에 의해 구현됩니다. 그러나 이것은 제가 가진 "직감"입니다.)
이 작업을 수행하는 더 빠르고 우아한 방법이 있습니까?
누구든지 나를 위해 이것을 정리할 수 있습니까?
두 가지 목적은 서로 다릅니다. 모든 개체의 ToString 메서드는 해당 개체의 문자열 표현을 반환해야합니다. 캐스팅은 상당히 다르며 'as'키워드는 이미 말했듯이 조건부 캐스팅을 수행합니다. 'as'키워드는 기본적으로 "해당 객체가이 유형 인 경우 해당 객체에 대한이 유형의 참조를 가져옵니다"라고 말하는 반면 ToString은 "해당 객체의 문자열 표현을 가져옵니다"라고 말합니다. 결과는 어떤 경우에는 동일 할 수 있지만 두 가지는 내가 말했듯이 서로 다른 목적으로 존재하기 때문에 상호 교환 가능한 것으로 간주해서는 안됩니다. 캐스트하려는 의도라면 항상 ToString이 아닌 캐스트를 사용해야합니다.
에서 http://www.codeguru.com/forum/showthread.php?t=443873
http://bytes.com/groups/net-c/225365-tostring-string-cast 참조
당신이 알고있는 경우는 인 String
모든 수단은으로 주조하여 다음 String
. 객체를 캐스팅하는 것이 가상 메서드를 호출하는 것보다 빠를 것입니다.
편집 : 일부 벤치마킹 결과는 다음과 같습니다.
============ Casting vs. virtual method ============
cast 29.884 1.00
tos 33.734 1.13
나는 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();
}
}
따라서 캐스팅은 실제로를 호출하는 것보다 약간 빠릅니다 ToString()
.
기본적으로 귀하의 경우 .ToString ()이 버그를 숨길 수 있기 때문에 유형 캐스트를 남겨 두는 것이 좋습니다. 예를 들어 데이터베이스 스키마가 변경되고 이름이 더 이상 문자열 유형이 아니지만 .ToString ()을 사용하면 코드가 계속 작동합니다. 따라서이 경우 유형 캐스트를 사용하는 것이 좋습니다.
다음은 String.ToString ()의 구현입니다-특별한 것은 없습니다 =)
public override string ToString()
{
return this;
}
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.
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.
In this scenario you have to use: string name = DataRowObject["name"].ToString() or
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";
}
For data object, I suggest you to use "as" keyword like the following code.
string name = DataRowObject["name"] as string;
Please check it before you use value.
if(name != null)
{
// statement for empty string or it has value
}
else
{
// statement for no data in this object.
}
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:
return this;
so IMHO there is no performance penalty.
PS I'm a Java programmer, so this anwser is only a guess.
ToString() does not perform a cast by default. Its purpose is to return a string that represents the type (e.g. "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.
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).
'IT TIP' 카테고리의 다른 글
Java 6 지원되지 않는 major.minor 버전 51.0 (0) | 2020.11.01 |
---|---|
C #의 예외는 얼마나 비쌉니까? (0) | 2020.11.01 |
pthreads 뮤텍스 대 세마포 (0) | 2020.11.01 |
HTML float right 요소 순서 (0) | 2020.11.01 |
Composer없이 Composer PHP 패키지를 설치하려면 어떻게해야합니까? (0) | 2020.11.01 |