your programing

null 가능성이있는 개체에 대해 ToString을 수행하는 방법은 무엇입니까?

lovepro 2020. 10. 6. 18:52
반응형

null 가능성이있는 개체에 대해 ToString을 수행하는 방법은 무엇입니까?


다음을 수행하는 간단한 방법이 있습니까?

String s = myObj == null ? "" : myObj.ToString();

다음을 수행 할 수 있다는 것을 알고 있지만 실제로는 해킹으로 간주합니다.

String s = "" + myObj;

Convert.ToString ()에 적절한 오버로드가 있으면 좋을 것입니다.


C # 6.0 편집 :

C # 6.0에서는 이제 간결하고 캐스트없는 버전의 orignal 메서드를 사용할 수 있습니다.

string s = myObj?.ToString() ?? "";

또는 보간을 사용하여 :

string s = $"{myObj}";

원래 답변 :

String s = (myObj ?? String.Empty).ToString();

또는

String s = (myObjc ?? "").ToString()

더 간결하게합니다.

불행히도 지적했듯이 비 String 또는 Object 유형에서이 작업을 수행하려면 양쪽에 캐스트가 필요한 경우가 많습니다.

String s = (myObjc ?? (Object)"").ToString()
String s = ((Object)myObjc ?? "").ToString()

따라서 우아하게 보일 수 있지만 캐스트는 거의 항상 필요하며 실제로는 그렇게 간결하지 않습니다.

다른 곳에서 제안했듯이 확장 방법을 사용하여 더 깔끔하게 만드는 것이 좋습니다.

public static string ToStringNullSafe(this object value)
{
    return (value ?? string.Empty).ToString();
}

string.Format("{0}", myObj);

string.Format은 null을 빈 문자열로 형식화하고 null이 아닌 객체에서 ToString ()을 호출합니다. 내가 이해하기 때문에 이것은 당신이 찾고 있던 것입니다.


Convert.ToString ()에 적절한 오버로드가 있으면 좋을 것입니다.

가있었습니다 Convert.ToString(Object value)닷넷 2.0 이후 (약 오년 전에 질문을 받았다이 Q.) 당신이 원하는 것을 정확히 할 나타납니다 :

http://msdn.microsoft.com/en-us/library/astxcyeh(v=vs.80).aspx

내가 여기서 정말 명백한 것을 놓치고 있거나 잘못 해석하고 있습니까?


확장 메서드를 사용하면 다음을 수행 할 수 있습니다.

public static class Extension
{
    public static string ToStringOrEmpty(this Object value)
    {
        return value == null ? "" : value.ToString();
    }
}

다음은 화면에 아무것도 쓰지 않고 예외를 throw하지 않습니다.

        string value = null;

        Console.WriteLine(value.ToStringOrEmpty());

나는 이것에 동의하지 않는다 :

String s = myObj == null ? "" : myObj.ToString();

어떤 식 으로든 해킹입니다. 명확한 코드의 좋은 예라고 생각합니다. 달성하려는 것이 무엇인지 그리고 null을 기대하고 있다는 것은 절대적으로 분명합니다.

최신 정보:

나는 당신이 이것이 해킹이라고 말하지 않았 음을 이제 알았습니다. 그러나 당신이이 방법이 갈 길이 아니라고 생각한다는 것은 질문에 내포되어 있습니다. 제 생각에는 확실히 가장 명확한 해결책입니다.


string s = String.Concat(myObj);

내가 추측하는 가장 짧은 방법이며 성능 오버 헤드도 무시할 수 있습니다. 의도가 무엇인지 코드 독자에게 명확하지 않을 수 있지만 명심하십시오.


사실 나는 당신이 무엇을하고 싶은지 이해하지 못했습니다. 내가 이해했듯이이 코드를 이와 같은 다른 방식으로 작성할 수 있습니다. 이건 물어 보는 건가요? 더 설명해 주시겠습니까?

string s = string.Empty;
    if(!string.IsNullOrEmpty(myObj))
    {
    s = myObj.ToString();
    }

내 대답에 맞을 수도 있지만 어쨌든 여기에 있습니다.

나는 단순히 쓸 것이다

string s = ""if (myObj! = null) {x = myObj.toString (); }

삼항 연산자를 사용하여 성능 측면에서 보답이 있습니까? 나는 내 머리 꼭대기에서 모른다.

And clearly, as someone above mentioned, you can put this behavior into a method such as safeString(myObj) that allows for reuse.


Holstebroe's comment would be your best answer:

string s = string.Format("{0}", myObj);

If myObj is null, Format places an Empty String value there.

It also satisfies your one line requirement and is easy to read.


I had the same problem and solved it by simply casting the object to string. This works for null objects too because strings can be nulls. Unless you absolutely don't want to have a null string, this should work just fine:

string myStr = (string)myObj; // string in a object disguise or a null

Some (speed) performance tests summarizing the various options, not that it really matters #microoptimization (using a linqpad extension)

Options

void Main()
{
    object objValue = null;
    test(objValue);
    string strValue = null;
    test(strValue);
}

// Define other methods and classes here
void test(string value) {
    new Perf<string> {
        { "coallesce", n => (value ?? string.Empty).ToString() },
        { "nullcheck", n => value == null ? string.Empty : value.ToString() },
        { "str.Format", n => string.Format("{0}", value) },
        { "str.Concat", n => string.Concat(value) },
        { "string +", n => "" + value },
        { "Convert", n => Convert.ToString(value) },
    }.Vs();
}

void test(object value) {
    new Perf<string> {
        { "coallesce", n => (value ?? string.Empty).ToString() },
        { "nullcheck", n => value == null ? string.Empty : value.ToString() },
        { "str.Format", n => string.Format("{0}", value) },
        { "str.Concat", n => string.Concat(value) },
        { "string +", n => "" + value },
        { "Convert", n => Convert.ToString(value) },
    }.Vs();
}

Probably important to point out that Convert.ToString(...) will retain a null string.

Results

Object

  • nullcheck 1.00x 1221 ticks elapsed (0.1221 ms) [in 10K reps, 1.221E-05 ms per]
  • coallesce 1.14x 1387 ticks elapsed (0.1387 ms) [in 10K reps, 1.387E-05 ms per]
  • string + 1.16x 1415 ticks elapsed (0.1415 ms) [in 10K reps, 1.415E-05 ms per]
  • str.Concat 1.16x 1420 ticks elapsed (0.142 ms) [in 10K reps, 1.42E-05 ms per]
  • Convert 1.58x 1931 ticks elapsed (0.1931 ms) [in 10K reps, 1.931E-05 ms per]
  • str.Format 5.45x 6655 ticks elapsed (0.6655 ms) [in 10K reps, 6.655E-05 ms per]

String

  • nullcheck 1.00x 1190 ticks elapsed (0.119 ms) [in 10K reps, 1.19E-05 ms per]
  • Convert 1.01x 1200 ticks elapsed (0.12 ms) [in 10K reps, 1.2E-05 ms per]
  • string + 1.04x 1239 ticks elapsed (0.1239 ms) [in 10K reps, 1.239E-05 ms per]
  • coallesce 1.20x 1423 ticks elapsed (0.1423 ms) [in 10K reps, 1.423E-05 ms per]
  • str.Concat 4.57x 5444 ticks elapsed (0.5444 ms) [in 10K reps, 5.444E-05 ms per]
  • str.Format 5.67x 6750 ticks elapsed (0.675 ms) [in 10K reps, 6.75E-05 ms per]

Even though this is an old question and the OP asked for C# I would like to share a VB.Net solution for those, who work with VB.Net rather than C#:

Dim myObj As Object = Nothing
Dim s As String = If(myObj, "").ToString()

myObj = 42
s = If(myObj, "").ToString()

Unfortunatly VB.Net doesn't allow the ?-operator after a variable so myObj?.ToString isn't valid (at least not in .Net 4.5, which I used for testing the solution). Instead I use the If to return an empty string in case myObj ist Nothing. So the first Tostring-Call return an an empty string, while the second (where myObj is not Nothing) returns "42".

참고URL : https://stackoverflow.com/questions/3987618/how-to-do-tostring-for-a-possibly-null-object

반응형