简体   繁体   English

在 C# 类之间传递值

[英]Passing values between C# classes

I'm quite new in the wonderful world of C# and I'm not sure how to cope with such a problem.我在 C# 的美妙世界中很新,我不知道如何应对这样的问题。

I have a .NET website on Visual Studio 2008, and I have a main page, main.aspx (with its following main.aspx.cs ) and a game page, game.aspx (also with game.aspx.cs ).我在 Visual Studio 2008 上有一个 .NET 网站,我有一个主页main.aspx (及其以下main.aspx.cs )和一个游戏页面game.aspx (也有game.aspx.cs )。

In the main class in main.aspx.cs I have a static variable, private static string _username;main.aspx.cs的主要 class 中,我有一个 static 变量, private static string _username; and with it, a method called getUsername that simply returns this value.有了它,一个名为 getUsername 的方法只返回这个值。

Now in my game class ( game.aspx.cs ) I have an event handler, saveButton_Click() , and in this function I need the value of _username !现在在我的游戏 class ( game.aspx.cs ) 我有一个事件处理程序saveButton_Click() ,在这个 function 我需要_username的值!

If it helps, a user starts on the main page, and then logs in... the variable _username is saved if the login is valid and then the user clicks a link to go to the game.aspx page!如果有帮助,用户从主页开始,然后登录...如果登录有效,则保存变量_username ,然后用户单击指向 go 的链接到game.aspx页面!

I've looked into the internal keyword, but I am not sure how to use it in this particular example or even if it's the right thing to do in this example!我已经查看了 internal 关键字,但我不确定如何在这个特定的示例中使用它,或者即使在这个示例中它是正确的做法!

To answer your question, you can make a public static property in a separate class.要回答您的问题,您可以在单独的 class 中创建公共 static 属性。

However, don't .但是,不要

This model will fail horribly (or worse) when two people use your site at once.当两个人同时使用您的网站时,此 model 将严重失败(或更糟)。

Instead, you should use Session State .相反,您应该使用Session State

Add this to your main page and game page classes:将此添加到您的主页和游戏页面类中:

protected string UserName {
    get { 
        string retVal=string.Empty;
        if (!string.IsNullOrEmpty(Session["UserName"]))
            retVal=Session["Username"].ToString();
        return retVal;
    }
    set{
        Session["UserName"]=value;
    }
}

and then access the property from your code;然后从您的代码中访问该属性;

You have to use Sessions to store and access the value in multiple pages:您必须使用Sessions来存储和访问多个页面中的值:

//To store value in session variable
Session["UserName"] = "UserName"; 

//To access the value in the session variable
String UserName = Session["UserName"];

Check for Details ASP.NET Session State检查详细信息ASP.NET Session State

IMHO, you could use Forms Based Authentication which would then make it very simple to get the user name, via User.Identity.Name .恕我直言,您可以使用基于 Forms 的身份验证,这将使通过User.Identity.Name获取用户名变得非常简单。

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

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