【问题标题】:How to give a value to a placeholder who is in a constant?如何给常量中的占位符赋值?
【发布时间】:2015-09-08 10:19:13
【问题描述】:

我有一个常量,它返回异常文本。在这个常量中,我有一个必须使用的占位符。我应该如何使用这个占位符?

这是我的代码:

public static class Messages
{
    public const string ShipDestroyed = "{0} has been destroyed";
}

我在另一个类中使用了这个方法中的常量:

protected void ValidateAlive(IStarship ship)
{
    if (ship.Health <= 0)
    {
        throw new ShipException(Messages.ShipDestroyed); 
    }
}

我想将“ship.Name”属性放入占位符中。

【问题讨论】:

  • 检查你的课程笔记总是个好主意 - 家庭作业经常涉及最近的主题(可能是“C#中的字符串格式”)。

标签: c# constants placeholder


【解决方案1】:

使用String.Format:

throw new ShipException(String.Format(Messages.ShipDestroyed, ship.Name));

如果你点击链接,你可以看到你可以用它做什么样的好东西。

【讨论】:

    猜你喜欢
    • 2020-06-26
    • 2020-07-31
    • 2011-08-20
    • 2017-09-23
    • 1970-01-01
    • 1970-01-01
    • 2014-04-30
    • 2020-03-24
    • 1970-01-01
    相关资源
    最近更新 更多