【问题标题】:C# If Contains?C#如果包含?
【发布时间】:2013-12-03 22:31:43
【问题描述】:

我是C# 的新手,我正在尝试编写包含语句。我希望进程读取test 变量,如果它包含单词错误,则打印该变量,如果它不包含错误,则不打印错误。我认为我的进程已经关闭,除非我在运行下面的代码时遇到 CLI 运行时出错。

“对象引用未设置为对象的实例”

任何帮助将不胜感激!

        while (true)
        {
            test = queue.GetMessage();
            if (test.AsString.Contains("error"))
            {
                Console.WriteLine(string.Format("Variable: {0}", test.AsString));

            }
            else
                Console.WriteLine(string.Format("No Error: {0}", test.AsString));
        }

【问题讨论】:

  • 你至少可以告诉我们错误发生在哪一行...
  • 也许你应该检查 if (test == null)。
  • 您的代码中有nulltest 或从 AsString 返回的任何内容。你为什么不覆盖ToString
  • 或者如果 AsString 为空。您可以为测试对象提供 ToString() 覆盖。
  • 同意尼姆。要么测试为空,要么队列从未完全定义/创建。

标签: c# visual-studio command-line-interface contains


【解决方案1】:

如果queue.GetMessage() 返回一个字符串,则不需要AsString。如果要将其转换为字符串,override ToString()

while (true) {
    test = queue.GetMessage();
    if (test.ToString().Contains("error")) {
        ...
    } else { 
        ...
    }
}

您始终可以保证ToString() 会出现,因为它是在object 基类中定义的。只要确保它返回一些可理解的东西,因为默认实现可能不会。

【讨论】:

    【解决方案2】:
    var message = queue.GetMessage()?? string.Empty;
    var formattedMessage =
                String.Format(
                    (message.IndexOf("error", StringComparison.OrdinalIgnoreCase) >= 0)
                        ? "No Error: {0}"
                        : "Variable: {0}", message);
    Console.WriteLine(formattedMessage);
    

    有用的参考资料:

    1. Unique ways to use the Null Coalescing operator
    2. Simplify conditional string format

    【讨论】:

    • String.Equals != 包含 ?
    • @abhitalks 很抱歉匆忙编辑.. 现在我已经纠正了错误
    猜你喜欢
    • 1970-01-01
    • 2017-10-02
    • 1970-01-01
    • 2013-01-08
    • 2012-01-07
    • 2013-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多