Convert.ToString ()과 .ToString ()의 차이점
차이점은 무엇이며 Convert.ToString()
그리고 .ToString()
?
온라인에서 많은 차이점을 발견했지만 주요 차이점은 무엇입니까?
Convert.ToString()
처리 null
하지만 ToString()
그렇지 않습니다.
ToString()
객체를 호출 하면 객체가 null이 아닌 것으로 가정합니다 (인스턴스 메소드를 호출하려면 객체가 있어야하기 때문에). Convert.ToString(obj)
객체가 null이 아니라고 가정 할 필요는 없지만 (Convert 클래스의 정적 메서드 String.Empty
이므로 ) null 인 경우 반환 됩니다 .
null
값 처리에 대한 다른 답변 외에도 base를 호출하기 전에 Convert.ToString
사용 IFormattable
및 IConvertible
인터페이스를 시도하십시오 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 ()
그렇지 않은 경우 NULLS를 처리 한다는 것입니다 . NULL 참조 예외 오류가 발생합니다. 따라서 올바른 코딩 방법 convert
은 항상 안전합니다.
클래스를 만들고 toString
메소드를 재정 의하여 원하는 작업을 수행 할 수 있습니다.
예를 들어 "MyMail" 클래스를 만들고 toString
전자 메일을 보내거나 현재 개체를 쓰는 대신 다른 작업을 수행 하도록 메서드를 재정의 할 수 있습니다 .
는 Convert.toString
동등한 지정된 값을 문자열 표현으로 변환한다.
object o=null;
string s;
s=o.toString();
//returns a null reference exception for string s.
string str=convert.tostring(o);
//returns an empty string for string str and does not throw an exception.,it's
//better to use convert.tostring() for good coding
null 처리를 제외하고 는 메소드는 "기본적으로"동일 합니다.
Pen pen = null;
Convert.ToString(pen); // No exception thrown
pen.ToString(); // Throws NullReferenceException
From MSDN :
Convert.ToString Method
Converts the specified value to its equivalent string representation.
Returns a string that represents the current object.
In Convert.ToString()
, the Convert handles either a NULL
value or not but in .ToString()
it does not handles a NULL
value and a NULL
reference exception error. So it is in good practice to use Convert.ToString()
.
For Code lovers this is the best answer.
.............. 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)
I agree with @Ryan's answer. By the way, starting with C#6.0 for this purpose you can use:
someString?.ToString() ?? string.Empty;
or
$"{someString}"; // I do not recommend this approach, although this is the most concise option.
instead of
Convert.ToString(someString);
ToString()
can not handle null values and convert.ToString()
can handle values which are null, so when you want your system to handle null value use convert.ToString()
.
Convert.ToString(strName)
will handle null-able values and strName.Tostring()
will not handle null value and throw an exception.
So It is better to use Convert.ToString()
then .ToString();
ToString() Vs Convert.ToString()
Similarities :-
Both are used to convert a specific type to string i.e int to string, float to string or an object to string.
Difference :-
ToString()
can't handle null while in case with Convert.ToString()
will handle null value.
Example :
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.
}
}
}
To understand both the methods let's take an example:
int i =0;
MessageBox.Show(i.ToString());
MessageBox.Show(Convert.ToString(i));
Here both the methods are used to convert the string but the basic difference between them is: Convert
function handles NULL
, while i.ToString()
does not it will throw a NULL reference exception error.
So as good coding practice using convert
is always safe.
Let's see another example:
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)
first tries casting obj to IConvertible, then IFormattable to call corresponding ToString(...)
methods. If instead the parameter value was null
then return string.Empty
. As a last resort, return obj.ToString()
if nothing else worked.
It's worth noting that Convert.ToString(value)
can return null
if for example value.ToString()
returns null.
i wrote this code and compile it.
class Program
{
static void Main(string[] args)
{
int a = 1;
Console.WriteLine(a.ToString());
Console.WriteLine(Convert.ToString(a));
}
}
by using 'reverse engineering' (ilspy) i find out 'object.ToString()' and 'Convert.ToString(obj)' do exactly one thing. infact 'Convert.ToString(obj)' call 'object.ToString()' so 'object.ToString()' is faster.
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);
}
}
Convert.Tostring() function handles the NULL whereas the .ToString() method does not. visit here.
참고URL : https://stackoverflow.com/questions/2828154/difference-between-convert-tostring-and-tostring
'development' 카테고리의 다른 글
내용에 맞게 UITableView 크기 조정 (0) | 2020.06.13 |
---|---|
새 Rails 앱을 만들 때 Rails에게 테스트 단위 대신 RSpec을 사용하도록 지시하려면 어떻게해야합니까? (0) | 2020.06.13 |
많은 UI 구성 요소가이를 필요로하기 때문에 호출 스레드는 STA이어야합니다. (0) | 2020.06.13 |
Python 목록을 CSV 파일로 작성 (0) | 2020.06.13 |
ConstraintLayout을 사용하여 균일 한 간격의 뷰 (0) | 2020.06.13 |