简体   繁体   English

IF块中的ASP.net C#变量声明

[英]ASP.net C# Variable Declaration Inside IF Block

I tried to use the following code in ASP.net C#: 我试图在ASP.net C#中使用以下代码:

@{
    var Host = Request.ServerVariables["HTTP_HOST"];
    if (Host.Contains("example.com")) {
        var Online = true;        
    }
    if (Online == true) {
        // Analytics Code
    }
}

But it returned error. 但是它返回了错误。

I found that variable Online cannot be used outside because its scope is limited to the IF statement in which it is declared. 我发现变量Online无法在外部使用,因为它的范围仅限于声明它的IF语句。

Through trial and error I found that the following code works: 通过反复试验,我发现以下代码有效:

@{
    var Host = Request.ServerVariables["HTTP_HOST"];
    if (Host.Contains("example.com")) {
        Page.Online = true;        
    }
    if (Page.Online == true) {
        // Analytics Code
    }
}

Why is this that the second snippet works although it should not because variable scopes are expected to end at closing } of IF statement? 为什么第二个代码段可以工作,尽管它不应该这样做,因为变量范围应该在IF语句的}结尾处结束?

Thanks 谢谢

Because in the 2nd statement, it does not declare a variable, but rather only set it's value. 因为在第二条语句中,它不声明变量,而是仅设置其值。 Page.Online was probably declared&initialized in the base class of the Page itself. Page.Online可能是在Page本身的基类中声明和初始化的。

Online is a variable : 在线是一个变量

var Online = true;

Page is an object . 页面是一个对象 It's actually a built-in object that belongs to the web request context you're operating in. It's also a dynamic object, which means it doesn't have a fixed type. 它实际上是一个内置对象,属于您在其中运行的Web请求上下文。它也是一个动态对象,这意味着它没有固定的类型。 Its type is inferred at runtime. 在运行时推断其类型。

Page.Online

Page.Online isn't a variable as such. Page.Online本身不是变量。 It's a dynamic property belonging to Page. 这是属于Page的动态属性。 One feature of dynamic objects is that you can assign anything to them, and all any method, and the compiler won't complain. 动态对象的一项功能是,您可以为它们分配任何内容以及所有任何方法,并且编译器不会抱怨。 It defers resolution until runtime, where its value is inferred from the context. 它将分辨率推迟到运行时,然后从上下文中推断出它的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM