繁体   English   中英

异常中的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 );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM