简体   繁体   English

asp.net C#变量

[英]asp.net C# variables

This is probably super simple and I'm sorry if I seem totally stupid but... 这可能是非常简单的,如果我看起来完全愚蠢,对不起,...

I'm coding my first asp.net web page for a class and I'm used to PHP 我正在为类编写我的第一个asp.net网页,并且习惯了PHP

in PHP when you create a variable in one block of code you can use it in all the others (as long as it has already be initialized) 在PHP中,当您在一个代码块中创建变量时,可以在所有其他代码块中使用它(只要它已被初始化)

Here is an example of what I mean: 这是我的意思的示例:

<?php $myVariable = "Hello World!" ?>

(later on in the code:) (稍后在代码中:)

<?php echo $myVariable; ?>

and In PHP that will work fine 并且在PHP中可以正常工作

Now the equivilant in asp as I understand it is: 现在,据我所知,asp中的等价物是:

<% String myVariable = "Hello World!"; %>

But when I try to use it in another block of code, the variable myVariable is not accessible 但是,当我尝试在另一个代码块中使用它时,变量myVariable无法访问

Am I doing something wrong? 难道我做错了什么?

The problem here is the scope of the variable. 这里的问题是变量的范围。 I would suggest you to go through this article at http://www.informit.com/articles/article.aspx?p=25467&seqNum=5 我建议您阅读http://www.informit.com/articles/article.aspx?p=25467&seqNum=5的这篇文章

Update 更新资料

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    string myVariable = "This is a variable";
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <%=myVariable %>
    </div>
    </form>
</body>
</html>

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

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