我是相当新的C#,并试图找出字符串插入(即"some {0} string", toInsert),以及跨一个问题跑我没想到......

在,你必须两个构造的情况下:

public MyClass(String arg1) { ... }

public MyClass(String arg1, String arg2) { ... }

是否有可能对我来说,有一个字符串插入使用第一个构造函数?

...
toInsert = "def"
myClass = new MyClass("abc{0}ghi", toInsert)
...

或者将C#解释为第二构造,并通过文字"abc{0}ghi"作为第一个参数?

有帮助吗?

解决方案

是,这将被解释为仅仅是第二个参数。

您所描述的行为称为字符串格式化并接受字符串这种风格家居使用的String.format()在后台运行。详情参见该方法的文档。

要获得所需的行为,使用以下代码:

myClass = new MyClass(string.Format("abc{0}ghi", toInsert));

其他提示

只要做到:

public MyClass(string format, params object[] args)
{
  this.FormattedValue = string.Format(format, args);
}
  

或者将C#解释此作为   第二构造,并通过一个文字   “ABC {0} GHI” 作为第一个参数?

这是正确的答案。 我认为,如果你使用的String.Format( “ABC {0} GHI”,toInsert),那么它会第一构造

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top