Development Tip

C #에서 .ToString과 "as string"의 차이점

yourdevel 2020. 11. 17. 21:13
반응형

C #에서 .ToString과 "as string"의 차이점


다음 두 문장을 사용하는 것의 차이점은 무엇입니까? 첫 번째 "문자열"은 유형 캐스트이고 두 번째 ToString은 입력을 문자열로 변환하는 메서드에 대한 실제 호출 인 것 같습니다. 그저 통찰력을 찾고 있습니다.

Page.Theme = Session["SessionTheme"] as string;
Page.Theme = Session["SessionTheme"].ToString();

경우 Session["SessionTheme"]아닌 string, as string돌아갑니다 null.

.ToString()객체의 ToString()메서드를 호출하여 다른 유형을 문자열로 변환하려고합니다 . 대부분의 내장 유형의 경우 문자열로 변환 된 객체를 반환하지만 특정 .ToString()메서드가 없는 사용자 정의 유형 의 경우 객체 유형의 이름을 반환합니다.

object o1 = "somestring";
object o2 = 1;
object o3 = new object();
object o4 = null;

string s = o1 as string;  // returns "somestring"
string s = o1.ToString(); // returns "somestring"
string s = o2 as string;  // returns null
string s = o2.ToString(); // returns "1"
string s = o3 as string;  // returns null
string s = o3.ToString(); // returns "System.Object"
string s = o4 as string;  // returns null
string s = o4.ToString(); // throws NullReferenceException

명심해야 할 또 다른 중요한 점은 객체가 인 null경우 호출 .ToString()하면 예외가 발생하지만 as string단순히를 반환한다는 것 null입니다.


as키워드는 기본적으로 대상 여부를 확인합니다 isMSIL 연산 코드를 사용하여 형식의 인스턴스를 isinst후드. 그럴 경우 개체에 대한 참조를 반환하고 그렇지 않으면 null 참조를 반환합니다.

그것은 않는 예외 처리의 일종을 의미한다 - 많은 말과 같이, 같은 캐스트를 수행하려고 시도하지. 별로.

ToString(), ToString()클래스에 의해 구현 된 사용자 지정 메서드 (대부분의 내장 형식에 대해 문자열로의 변환을 수행함) 또는 제공되지 않은 경우 기본 클래스 메서드 를 호출하여 object형식 정보를 반환합니다.


Page.Theme = Session["SessionTheme"] as string;

문자열로 캐스팅하려고

이므로

Page.Theme = Session["SessionTheme"].ToString;

정말 무엇이든 될 수있는 tostring 메서드를 호출합니다. 이 메서드는 캐스트되지 않으며이 개체의 문자열 표현을 반환해야합니다.


우선 " any-object as string "및 " any-object.ToString () "은 각각의 컨텍스트 측면에서 완전히 다른 것입니다.

string str = any-object as string;

1) 이것은 임의의 객체를 문자열 유형으로 캐스팅하고 임의의 객체가 문자열로 캐스팅 할 수없는 경우이 문은 예외를 발생시키지 않고 null을 반환합니다.
2) 이것은 컴파일러 서비스입니다.
3) 이것은 문자열 이외의 다른 유형에 대해 매우 잘 작동합니다. 예 : Employee와 같이 모든 객체로 수행 할 수 있습니다. 여기서 Employee는 라이브러리에 정의 된 클래스입니다.

string str = any-object.ToString();  

1) 이것은 유형 정의에서 모든 객체의 ToString ()을 호출합니다. System.Object는 ToString () 메서드를 정의하므로 .Net 프레임 워크의 모든 클래스에는 재정의에 사용할 수있는 ToString () 메서드가 있습니다. 프로그래머는 모든 객체 클래스 또는 구조체 정의에서 ToString ()을 재정의하고 모든 객체가 수행하는 역할과 책임에 따라 모든 객체의 적절한 문자열 표현을 반환하는 코드를 작성합니다.
2) Employee 클래스를 정의하고 Employee 객체의 문자열 표현을 "FIRSTNAME-LASTNAME, EMP-CDOE"로 반환 할 수있는 ToString () 메서드를 재정의 할 수 있습니다.

이 경우 프로그래머는 ToString ()을 제어 할 수 있으며 캐스팅 또는 유형 변환과는 아무 관련이 없습니다.


문제를 더 혼동하기 위해 C # 6.0은 null-conditional operator를 도입했습니다 . 이제 다음과 같이 작성할 수도 있습니다.

Page.Theme = Session["SessionTheme"]?.ToString();

예외를 throw하지 않고 null 또는 ToString ()의 결과를 반환합니다.


Philippe Leybaert의 대답을 조금 확장하고 있습니다.이 중 세 가지를 비교하는 리소스를 찾았지만 네 가지를 모두 비교하는 설명을 찾지 못했기 때문입니다.

  • (string)obj
  • obj as string
  • obj.ToString()
  • Convert.ToString(obj)
object o1 = "somestring";
object o2 = 1;
object o3 = new object();
object o4 = null;

Console.WriteLine((string)o1);           // returns "somestring"
Console.WriteLine(o1 as string);         // returns "somestring"
Console.WriteLine(o1.ToString());        // returns "somestring"
Console.WriteLine(Convert.ToString(o1)); // returns "somestring"
Console.WriteLine((string)o2);           // throws System.InvalidCastException
Console.WriteLine(o2 as string);         // returns null
Console.WriteLine(o2.ToString());        // returns "1"
Console.WriteLine(Convert.ToString(o2)); // returns "1"
Console.WriteLine((string)o3);           // throws System.InvalidCastException
Console.WriteLine(o3 as string);         // returns null
Console.WriteLine(o3.ToString());        // returns "System.Object"
Console.WriteLine(Convert.ToString(o3)); // returns "System.Object"
Console.WriteLine((string)o4);           // returns null
Console.WriteLine(o4 as string);         // returns null
Console.WriteLine(o4.ToString());        // throws System.NullReferenceException
Console.WriteLine(Convert.ToString(o4)); // returns ""

From these results we can see that (string)obj and obj as string behave the same way as each other when obj is a string or null; otherwise (string)obj will throw an invalid cast exception and obj as string will just return null. obj.ToString() and Convert.ToString(obj) also behave the same way as each other except when obj is null, in which case obj.ToString() will throw a null reference exception and Convert.ToString(obj) will return an empty string.

So here are my recommendations:

  • (string)obj works best if you want to throw exceptions for types that can't be assigned to a string variable (which includes null)
  • obj as string works best if you don't want to throw any exceptions and also don't want string representations of non-strings
  • obj.ToString() works best if you want to throw exceptions for null
  • Convert.ToString(obj) works best if you don't want to throw any exceptions and want string representations of non-strings

The as string check is the object is a string. If it isn't a null it returned.

The call to ToString() will indeed call the ToString() method on the object.


The first one returns the class as a string if the class is a string or derived from a string (returns null if unsuccessful).

The second invokes the ToString() method on the class.


Actually the best way of writing the code above is to do the following:

if (Session["SessionTheme"] != null)
{
    Page.Theme = Session["SessionTheme"].ToString();
}

That way you're almost certain that it won't cast a NullReferenceException.

참고URL : https://stackoverflow.com/questions/2099900/difference-between-tostring-and-as-string-in-c-sharp

반응형