如何通过if语句控制输出

时间:2019-07-05 10:51:51

标签: c# .net if-statement console.writeline

if (vm.Name != null)
{
    Console.WriteLine("VM name is \"{0}\" and ID is \"{1}\". State is: \"{2}\". Location: \"{3}\" and the Instance Type is \"{4}\". Key is \"{5}\".",
        vm.Name, vm.InstanceId, vm.State, vm.Region, vm.InstanceType, vm.KeyName);
}
else
{
    Console.WriteLine("VM ID is \"{0}\". State is: \"{1}\". Location: \"{2}\" and the Instance Type is \"{3}\". Key is \"{4}\".",
        vm.InstanceId, vm.State, vm.Region, vm.InstanceType, vm.KeyName);
}

我正在尝试在此处进行尽可能少的复制粘贴。我的问题是如何缩小此代码,以便仅对信息的第一位vm.Name而不对整个输出行仅应用 if语句

6 个答案:

答案 0 :(得分:3)

您可以使用

    //Here you will check condition and format first few words of sentences
    var str = vm.Name != null ? $"name is {vm.Name} and " : string.Empty;
    //if name is not null then add it to zeroth position otherwise add empty string
    Console.WriteLine($"VM {str}ID is {vm.InstanceId}. State is: {vm.State}. Location: {vm.Region} and the Instance Type is {vm.InstanceType}. Key is {vm.KeyName}.");

奖金:.net fiddle

答案 1 :(得分:2)

使用表达式。像这样:

Console.WriteLine(
    "VM {0}ID is \"{1}\". State is: \"{2}\". Location: \"{3}\" and the Instance Type is \"{4}\". Key is \"{5}\".",
    vm.Name != null ? $"name is \"{vm.Name}\" and " : string.Empty, vm.InstanceId,
    vm.State, vm.Region, vm.InstanceType, vm.KeyName);

答案 2 :(得分:0)

var firstPart = string.Empty;
if (vm.Name != null)
{
    firstPart = $"VM name is {vm.Name}";
}
else
{
    firstPart = $"VM ID is {vm.InstanceId}";            
}

Console.WriteLine($"{firstPart}. State is: {vm.State}. Location: {vm.Region} and the Instance Type is { vm.InstanceType}. Key is {vm.KeyName}.");

您可以更改firstPart变量的名称。没有比这更好的了。

答案 3 :(得分:0)

您知道的零件是否一直存在并替换它...?这不是最好的,但应该可以。

var output = string.Format("VM ID is \"{0}\". State is: \"{1}\". Location: \"{2}\" and the Instance Type is \"{3}\". Key is \"{4}\".",
             vm.InstanceId, vm.State, vm.Region, vm.InstanceType, vm.KeyName);

if (vm.Name != null) {
    output.Replace("VM ", $"VM name is "\"{vm.Name}\" ")
}

答案 4 :(得分:0)

您可以将Name属性声明为可空

做这样的事情:

string val;
            if (vm.Name != null)
            {
                val = "VM name is \"{0}\" and";
            }
            else
            {
                val = "VM";
            }
            Console.WriteLine(
                  val + " ID is \"{1}\". State is: \"{2}\". Location: \"{3}\" and the Instance Type is \"{4}\". Key is \"{5}\".",
                  vm.Name, vm.InstanceId,
                  vm.State, vm.Region, vm.InstanceType, vm.KeyName);

答案 5 :(得分:0)

我会这样做。尼斯,容易和可读。

string VmName = "";

if(vm.Name != null)
  VmName = "name is \"" + vm.Name + "\" and"; 

Console.WriteLine("VM " + VmName + " ID is \"{0}\". State is: \"{1}\". Location: \"{2}\" and the Instance Type is \"{3}\". Key is \"{4}\".",
                 vm.InstanceId, vm.State, vm.Region, vm.InstanceType, vm.KeyName);