异常中的 C# 占位符
C# Placeholders in Exceptions
愚蠢的问题,但我真的找不到答案。
你怎么能在这样的异常中插入一个占位符?
甚至有可能吗?
public int Age
{
get
{
return this.age;
}
set
{
this.age = value;
if((0 >= value) || (value > 100))
{
throw new ArgumentOutOfRangeException("The age {0} you've entered must be in the range [1..100]",value);
}
}
}
您可以将 string.Format
与 {0}、{1}...等一起使用。占位符:
throw new ArgumentOutOfRangeException(string.Format(
"The age {0} you've entered must be in the range [1..100]",
value));
由于 ArgumentOutOfRangeException
需要一个字符串,您不能直接将占位符传递给它。要构造带占位符的字符串,您应该使用 string.Format()
方法。这给出了格式化的字符串。
string message = string.Format("The age {0} you've entered must be in the range [1..100]" ,value);
throw new ArgumentOutOfRangeException( message );
愚蠢的问题,但我真的找不到答案。 你怎么能在这样的异常中插入一个占位符? 甚至有可能吗?
public int Age
{
get
{
return this.age;
}
set
{
this.age = value;
if((0 >= value) || (value > 100))
{
throw new ArgumentOutOfRangeException("The age {0} you've entered must be in the range [1..100]",value);
}
}
}
您可以将 string.Format
与 {0}、{1}...等一起使用。占位符:
throw new ArgumentOutOfRangeException(string.Format(
"The age {0} you've entered must be in the range [1..100]",
value));
由于 ArgumentOutOfRangeException
需要一个字符串,您不能直接将占位符传递给它。要构造带占位符的字符串,您应该使用 string.Format()
方法。这给出了格式化的字符串。
string message = string.Format("The age {0} you've entered must be in the range [1..100]" ,value);
throw new ArgumentOutOfRangeException( message );