I'm fairly new to C#, and trying to figure out string insertions (i.e. "some {0} string", toInsert
), and ran across a problem I wasn't expecting...
我对C#很新,并试图找出字符串插入(即“some {0} string”,toInsert),并遇到了一个我没想到的问题......
In the case where you have two constructors:
如果您有两个构造函数:
public MyClass(String arg1) { ... }
public MyClass(String arg1, String arg2) { ... }
Is it possible for me to use the first constructor with a string insertion?
我可以使用带有字符串插入的第一个构造函数吗?
...
toInsert = "def"
myClass = new MyClass("abc{0}ghi", toInsert)
...
Or will C# interpret this as the second constructor and pass a literal "abc{0}ghi"
as the first argument?
或者C#会将其解释为第二个构造函数,并将文字“abc {0} ghi”作为第一个参数传递?
3 个解决方案
#1
Yes, this will be interpreted as just a second parameter.
是的,这将被解释为第二个参数。
The behavior you describe is called string formatting and everything that accepts strings in this style uses string.Format() in the background. See the documentation of that method for details.
您描述的行为称为字符串格式,接受此样式字符串的所有内容在后台使用string.Format()。有关详细信息,请参阅该方法的文档。
To get the desired behavior, use this code:
要获得所需的行为,请使用以下代码:
myClass = new MyClass(string.Format("abc{0}ghi", toInsert));
#2
Just do:
public MyClass(string format, params object[] args)
{
this.FormattedValue = string.Format(format, args);
}
#3
Or will C# interpret this as the second constructor and pass a literal "abc{0}ghi" as the first argument?
或者C#会将其解释为第二个构造函数,并将文字“abc {0} ghi”作为第一个参数传递?
This is the right answer. I think If you use String.Format("abc{0}ghi", toInsert) then it will take the first constructor
这是正确的答案。我想如果你使用String.Format(“abc {0} ghi”,toInsert)那么它将采用第一个构造函数
#1
Yes, this will be interpreted as just a second parameter.
是的,这将被解释为第二个参数。
The behavior you describe is called string formatting and everything that accepts strings in this style uses string.Format() in the background. See the documentation of that method for details.
您描述的行为称为字符串格式,接受此样式字符串的所有内容在后台使用string.Format()。有关详细信息,请参阅该方法的文档。
To get the desired behavior, use this code:
要获得所需的行为,请使用以下代码:
myClass = new MyClass(string.Format("abc{0}ghi", toInsert));
#2
Just do:
public MyClass(string format, params object[] args)
{
this.FormattedValue = string.Format(format, args);
}
#3
Or will C# interpret this as the second constructor and pass a literal "abc{0}ghi" as the first argument?
或者C#会将其解释为第二个构造函数,并将文字“abc {0} ghi”作为第一个参数传递?
This is the right answer. I think If you use String.Format("abc{0}ghi", toInsert) then it will take the first constructor
这是正确的答案。我想如果你使用String.Format(“abc {0} ghi”,toInsert)那么它将采用第一个构造函数