string.Format上有{<img src="https://i.stack.imgur.com/gUdYe.jpg" alt="Table example"/>}做什么?

时间:2016-07-18 12:34:21

标签: c# lazy-evaluation

在命名空间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);

这是多么的懒惰&#39;?懒惰是做什么的?

reference source的完整课程:

//---------------------------------------------------------------------------- 
//
// <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.

4 个答案:

答案 0 :(得分:66)

escape a curly brace with a curly brace,即{{生成{}}生成}

中间的{0}被解释为通常 - 即对零指数参数的引用。

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

最终结果是用花括号括起来的参数零值:

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

那个'懒惰'怎么样?

对于这种替代性的“渴望”实施,他们称之为懒惰:

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;
}

此实现立即添加大括号,即使它不知道将需要括在大括号中的名称。

答案 1 :(得分:15)

  

这是多么的懒惰&#39;?懒惰是做什么的?

懒惰来自它之前的if (_name[0] != '{')

它仅在第一次请求时更改_name字段。

就像所有人已经指出的那样,String.Format("{{{0}}}", _name);应该被理解为"{{ {0} }}""\{ {0} \}"。内部{0}是要用第一个参数替换的实际字段,外部{{}}是获取单个{}的特殊符号

答案 2 :(得分:10)

{{}}只会为您提供文字{}。 (Escaped花括号)

所以,如果您有{{{0}}},并且同意foo,则输出将为{foo}

答案 3 :(得分:6)

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