如何通过if语句控制输出

How to control output by if statement

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);
}

我尽量少复制粘贴到这里。我的问题是如何缩小此代码,以便仅将 if-statement 应用于信息的第一位 vm.Name 而不是整个输出行?

您可以使用类似

    //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

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 变量的名称。没有比这更好的了。

做你知道它总是有的部分并更换它......?这不是最好的,但应该可以。

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}\" ")
}

使用表达式。像这样:

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);

您可以将 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);

我会这样做。不错,简单易读。

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);