如何在asp.net c#内完成代码执行(IF,否则IF,IF,IF)

时间:2015-11-08 01:18:22

标签: c#

我正在开发一个asp.net mvc 5 Web应用程序。现在我有以下内容: -

    IF(condition1)
{
//1
}
    else if (condition 2)
{
//2
}
    IF(condition3)
{
//3
}
    IF(condition4)
{
//4
}

那么如何在我的应用程序中执行呢? 以下是: -

  1. 如果条件1通过则conditio2永远不会被检查,条件3&条件4将始终被检查?如果condition1失败,那么将检查condition2以及condition3& 4将被检查?

2 个答案:

答案 0 :(得分:2)

对代码添加一些缩进将清除您的问题

// Test values, change them to change the output
int c1 = 1;
int c2 = 2;
int c3 = 3;
int c4 = 4;

if(c1 == 1)
    Console.WriteLine("Condition1 is true");
else if (c2 == 2)
    if(c3 == 3)
        if(c4 == 4)
            Console.WriteLine("Condition2,3 and 4 are true");
        else
            Console.WriteLine("Condition4 is false but 3 and 2 are true");
    else
        Console.WriteLine("Condition3 is false but 2 is true");
else
    Console.WriteLine("Condition1 and 2 are false");

在您的示例中,如果条件为真,则没有花括号来分隔要执行的语句块,因此ifs以第一个分号结束。

如果condition1为真,则会评估else链中的任何内容,因为condition34上的ifs取决于condition1为false和condition2是真的。

如果condition1为false,则评估condition2,如果为true,则代码会检查condition3并检查condition4 condition3是否为if(c1 == 1) Console.WriteLine("Condition1 is true"); else if (c2 == 2 && c3 == 3 && c4 == 4) Console.WriteLine("Condition2,3, and 4 are true"); 真,

当然,根据您需要对输入值执行的操作,可以将其简单地写为

if(condition1)
{
    // enters here if condition1 is true, thus the condition2 is not evaluated
}
else if (condition 2)
{
    // enters here if condition1 is evaluated and is false, 
    // but the condition2 is true 
}


if(condition3)
{
   // enters here if condition3 is true, indipendently from the
   // result of the evaluation of condition1 and 2 
}
if(condition4)
{
   // enters here if condition3 is true, indipendently from the
   // result of the evaluation of condition1 and 2 
}

编辑

现在添加大括号后,代码行为完全不同

#!/usr/bin/perl

use strict;
use warnings;

my @ARGV     = <STDIN>;
my $filename = $ARGV[0];
my $word     = 0;
my %freq     = ();
my @wordarray;

open( FILE, $filename );

while ( <STDIN> ) {

    if ( scalar( @ARGV ) > 1 ) {

        if ( $ARGV[1] eq "-i" ) {

            my $string = $_;
            $string =~ tr/A-Z/a-z/;
            tr/A-Za-z/ /cs;
            my @wordarray = ( split( ' ', lc $string ) );

            foreach my $word ( @wordarray ) {
                $freq{$word}++;
            }
        }
    }

    if ( scalar( @ARGV ) < 2 ) {

        my $string = $_;
        tr/A-Za-z/ /cs;
        my @wordarray = ( split( ' ', $string ) );

        foreach my $word ( @wordarray ) {
            $freq{$word}++;
        }
    }
}

foreach $word ( sort keys %freq ) {
    print "$word $freq{$word}\n";
}

close( FILE );

答案 1 :(得分:1)

始终会检查

3和4。 1被检查,如果为真,则忽略2,因为它在else if下,但如果1是false,那么将评估2。

相关问题