Convert.ToString()과 의 차이점은 무엇입니까 .ToString()?
온라인에서 많은 차이점을 발견했지만 가장 큰 차이점은 무엇입니까?
Convert.ToString()과 의 차이점은 무엇입니까 .ToString()?
온라인에서 많은 차이점을 발견했지만 가장 큰 차이점은 무엇입니까?
답변:
Convert.ToString()핸들 null, 동안은 ToString()하지 않습니다.
null예외를 빈 문자열을 반환하거나 던져? 캐스팅과 사용의 차이와 비슷합니다 as.
ToString()객체에 대한 호출 은 객체가 null이 아니라고 가정합니다 (객체가 인스턴스 메서드를 호출하려면 존재해야하기 때문). Convert.ToString(obj)(이 변환 클래스에 정적의 방법으로), 대신 반환 객체를 추정 할 필요가 없습니다 것은 null는 아니고, String.Empty이 경우 입니다 NULL을.
Convert.ToString(string value)반환 null합니다 null. 인수가 인 경우를 Convert.ToString(object value)반환 String.Empty합니다 null.
null값 처리에 대한 다른 답변 외에도 Convert.ToString사용을 시도 IFormattable하고IConvertible base를 호출하기 전에 인터페이스Object.ToString .
예:
class FormattableType : IFormattable
{
private double value = 0.42;
public string ToString(string format, IFormatProvider formatProvider)
{
if (formatProvider == null)
{
// ... using some IOC-containers
// ... or using CultureInfo.CurrentCulture / Thread.CurrentThread.CurrentCulture
formatProvider = CultureInfo.InvariantCulture;
}
// ... doing things with format
return value.ToString(formatProvider);
}
public override string ToString()
{
return value.ToString();
}
}
결과:
Convert.ToString(new FormattableType()); // 0.42
new FormattableType().ToString(); // 0,42
이 예제를 통해 차이점을 이해하겠습니다.
int i= 0;
MessageBox.Show(i.ToString());
MessageBox.Show(Convert.ToString(i));
우리는 정수를 변환 할 수 있습니다 i사용 i.ToString ()하거나 Convert.ToString. 그렇다면 차이점은 무엇입니까?
그들 사이의 기본적인 차이점은 Convert함수는 NULLS를 처리하지만 i.ToString ()그렇지 않다는 것입니다. NULL 참조 예외 오류가 발생합니다. 따라서 좋은 코딩 연습 convert은 항상 안전합니다.
클래스를 만들고 toString원하는 작업을 수행 하도록 메서드를 재정의 할 수 있습니다.
예를 들어 "MyMail" 클래스를 만들고 toString메서드를 재정 의하여 현재 개체를 작성하는 대신 전자 메일을 보내거나 다른 작업을 수행 할 수 있습니다.
는 Convert.toString동등한 지정된 값을 문자열 표현으로 변환한다.
메서드는 null 처리를 제외하고 "기본적으로"동일 합니다.
Pen pen = null;
Convert.ToString(pen); // No exception thrown
pen.ToString(); // Throws NullReferenceException
MSDN에서 :
Convert.ToString 메서드
지정된 값을 해당하는 문자열 표현으로 변환합니다.
현재 개체를 나타내는 문자열을 반환합니다.
null, ""또는 "null"?
코드 애호가에게는 이것이 최선의 대답입니다.
.............. Un Safe code ...................................
Try
' In this code we will get "Object reference not set to an instance of an object." exception
Dim a As Object
a = Nothing
a.ToString()
Catch ex As NullReferenceException
Response.Write(ex.Message)
End Try
'............... it is a safe code..............................
Dim b As Object
b = Nothing
Convert.ToString(b)
Convert.ToString(strName) null 허용 값을 처리하고 strName.Tostring() NULL 값을 처리하고 예외를 발생하지 않습니다.
그것은 더 나은 그래서 사용 Convert.ToString()후.ToString();
ToString() Vs Convert.ToString()
유사점 :-
둘 다 특정 유형을 문자열로 변환하는 데 사용됩니다. 즉, int를 문자열로, float를 문자열로 또는 객체를 문자열로 변환합니다.
차이 :-
ToString()Convert.ToString()null 값을 처리하는 경우 null을 처리 할 수 없습니다 .
예 :
namespace Marcus
{
class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
class Startup
{
public static void Main()
{
Employee e = new Employee();
e = null;
string s = e.ToString(); // This will throw an null exception
s = Convert.ToString(e); // This will throw null exception but it will be automatically handled by Convert.ToString() and exception will not be shown on command window.
}
}
}
Convert.ToString처리하지 마십시오 Null Exception. 단순히 수행return value == null ? string.Empty : value.ToString()
두 가지 방법을 모두 이해하기 위해 예를 들어 보겠습니다.
int i =0;
MessageBox.Show(i.ToString());
MessageBox.Show(Convert.ToString(i));
여기서 두 메서드는 모두 문자열을 변환하는 데 사용되지만 기본 차이점은 다음과 같습니다. Convertfunction handles NULL, i.ToString()그렇지 않은 경우 NULL reference exception error.So를 throw하는 좋은 코딩 방법 convert은 항상 안전합니다.
다른 예를 보겠습니다.
string s;
object o = null;
s = o.ToString();
//returns a null reference exception for s.
string s;
object o = null;
s = Convert.ToString(o);
//returns an empty string for s and does not throw an exception.
Convert.ToString(value)먼저 obj를 IConvertible로 캐스팅 한 다음 IFormattable 을 사용하여 해당 ToString(...)메서드 를 호출 합니다. 대신 매개 변수 값이 null이면을 반환 string.Empty합니다. 최후의 수단으로 obj.ToString()다른 방법이 효과가 없으면 반환 하십시오.
예를 들어 null을 반환 하면 반환 Convert.ToString(value) 할 수 있다는 점 은 주목할 가치가 있습니다 .nullvalue.ToString()
참조 닷넷 참조 소스를
이 코드를 작성하고 컴파일합니다.
class Program
{
static void Main(string[] args)
{
int a = 1;
Console.WriteLine(a.ToString());
Console.WriteLine(Convert.ToString(a));
}
}
'역 공학'( ilspy ) 을 사용하여 ' object.ToString ()'과 'Convert.ToString (obj)'가 정확히 한 가지를 수행한다는 것을 알았 습니다. 사실 'Convert.ToString (obj)'는 'object.ToString ()'을 호출하므로 'object.ToString ()'이 더 빠릅니다.
class System.Object
{
public string ToString(IFormatProvider provider)
{
return Number.FormatInt32(this, null, NumberFormatInfo.GetInstance(provider));
}
}
class System.Convert
{
public static string ToString(object value)
{
return value.ToString(CultureInfo.CurrentCulture);
}
}