在静态类中访问非静态类的值

时间:2009-10-22 05:46:00

标签: c# static

ASP.NET C#中的

。如何从非静态类.edx中存在的值设置静态类的变量值:我有一个名为staticA的静态类和一个名为B的非静态类inhertits system .WEb.UI.Page。我在B类中有一些值,我想将其设置为静态类A的属性值,以便我可以在整个项目中使用它

有什么想法?

3 个答案:

答案 0 :(得分:3)

staticA.AValue = b.BValue

答案 1 :(得分:2)

“正确”的方法是将您的特定实例传递给B(不要将类及其实例混淆!!!)到A的方法它将复制它需要的任何属性(或其他值)。

答案 2 :(得分:1)

参见以下示例:

 public static class staticA 
{
    /// <summary>
    /// Global variable storing important stuff.
    /// </summary>
    static string _importantData;

    /// <summary>
    /// Get or set the static important data.
    /// </summary>
    public static string ImportantData
    {
        get
        {
            return _importantData;
        }
        set
        {
            _importantData = value;
        }
    }
}

和在classB

public partial class _classB : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // 1.
        // Get the current ImportantData.
        string important1 = staticA.ImportantData;

        // 2.
        // If we don't have the data yet, initialize it.
        if (important1 == null)
        {
            // Example code only.
            important1 = DateTime.Now.ToString();
            staticA.ImportantData = important1;
        }

        // 3.
        // Render the important data.
        Important1.Text = important1;
    }
}

希望,它有所帮助。

相关问题