开发者

Accessing value of a non static class in a static class

开发者 https://www.devze.com 2022-12-08 23:04 出处:网络
in ASP.NET C#., How can i set the variable values of a static class from the value present in a non static class .edx : I have a static class called staticA and a non static class called B which inher

in ASP.NET C#., How can i set the variable values of a static class from the value present in a non static class .edx : I have a static class called staticA and a non static class called B which inhertits system.WEb.UI.Page. I have some values present in the class B ,which i want to se开发者_如何学编程t as the property value of the static class A so that i can use it throughout the project

Any thoughts ?


staticA.AValue = b.BValue


The "proper" approach would be to pass your specific instance of B (don't confuse a class and its instances!!!) to a method of A which will copy whatever properties (or other values) it needs to.


See following example:

 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;
        }
    }
}

and in 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;
    }
}

Hope, It helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消