IT Share you

string.Format의 {{{0}}}은 무엇을합니까?

shareyou 2021. 1. 7. 19:53
반응형

string.Format의 {{{0}}}은 무엇을합니까?


네임 스페이스 MS.Internal에는라는 클래스가 NamedObject있습니다.

이상한 코드 블록이 있습니다.

public override string ToString()
{
  if (_name[0] != '{')
  {
    // lazily add {} around the name, to avoid allocating a string 
    // until it's actually needed
    _name = String.Format(CultureInfo.InvariantCulture, "{{{0}}}", _name);
  }

  return _name;
}

이 댓글에 대해 구체적으로 궁금합니다.

    // lazily add {} around the name, to avoid allocating a string 
    // until it's actually needed
    _name = String.Format(CultureInfo.InvariantCulture, "{{{0}}}", _name);

어떻게 '게으른'가요? 게으 르기 위해 무엇을합니까?


참조 소스의 전체 클래스 :

//---------------------------------------------------------------------------- 
//
// <copyright file="NamedObject.cs" company="Microsoft">
//    Copyright (C) Microsoft Corporation.  All rights reserved.
// </copyright> 
//
// Description: Placeholder object, with a name that appears in the debugger 
// 
//---------------------------------------------------------------------------

using System;
using System.Globalization;
using MS.Internal.WindowsBase;

namespace MS.Internal
{
  /// <summary> 
  /// An instance of this class can be used wherever you might otherwise use
  /// "new Object()".  The name will show up in the debugger, instead of 
  /// merely "{object}"
  /// </summary>
  [FriendAccessAllowed]   // Built into Base, also used by Framework.
  internal class NamedObject
  {
    public NamedObject(string name)
    {
      if (String.IsNullOrEmpty(name))
        throw new ArgumentNullException(name);

      _name = name;
    }

    public override string ToString()
    {
      if (_name[0] != '{')
      {
        // lazily add {} around the name, to avoid allocating a string 
        // until it's actually needed
        _name = String.Format(CultureInfo.InvariantCulture, "{{{0}}}", _name);
      }

      return _name;
    }

    string _name;
  }
}

// File provided for Reference Use Only by Microsoft Corporation (c) 2007.
// Copyright (c) Microsoft Corporation. All rights reserved.

당신은 중괄호와 중괄호를 탈출 즉, {{생산 {}}생산 }.

{0}인덱스 제로의 매개 변수 즉 참조 - 중간에 평소처럼 해석됩니다.

{{ {0} }}
^^ ^^^ ^^
|   |  |
|   |  +--- Closing curly brace
|   +------ Parameter reference
+---------- Opening curly brace

최종 결과는 중괄호로 묶인 매개 변수 0의 값입니다.

var res = string.Format("{{{0}}}", "hello"); // produces {hello}

어떻게 '게으른'가요?

그들은이 대안적인 "간단한"구현과 관련하여 그것을 lazy라고 부릅니다.

internal class NamedObject {
    public NamedObject(string name) {
        if (String.IsNullOrEmpty(name))
            throw new ArgumentNullException(name);
        if (name[0] != '{') {
            // eagerly add {} around the name
            _name = String.Format(CultureInfo.InvariantCulture, "{{{0}}}", name);
        } else {
            _name = name;
        }
    }
    public override string ToString() {
        return _name;
    }
    string _name;
}

This implementation adds curly braces right away, even though it has no idea that the name enclosed in curly braces is going to be needed.


How is that 'lazy'? What does it do to be lazy?

The laziness comes from the if (_name[0] != '{') before it.

It only changes the _name field when it is requested for the first time.

And like everybody already pointed out, String.Format("{{{0}}}", _name); should be read as "{{ {0} }}" or "\{ {0} \}". The inner {0} is the actual field to substitute with the first argument, the outer {{ and }} are a special notation to get single {}


{{ and }} just give you literal { and }. (Escaped curly braces)

so, if you have {{{0}}}, and you give along foo, the output will be {foo}


var value = "value";
String.Format(CultureInfo.InvariantCulture, "{{{0}}}", value); // will output {value}

ReferenceURL : https://stackoverflow.com/questions/38436847/what-does-0-on-string-format-do

반응형