开发者

Using an Instantiated Class in another Class

开发者 https://www.devze.com 2023-02-26 04:43 出处:网络
Please excuse my ignorance, I am transitioning from VB6 to C# (very steep learning curve). I have googled this to death and I am not able to figure this out. I instantiated a Class on my main form:

Please excuse my ignorance, I am transitioning from VB6 to C# (very steep learning curve). I have googled this to death and I am not able to figure this out. I instantiated a Class on my main form:

namespace App1_Name
{
    public partial class Form1 : Form
    {
开发者_运维知识库        public cConfig Config = new cConfig();
    }
}

In my Config Class I am instantiating two other classes:

namespace App1_Name
{
    class cConfig
    {
        //Properties
        public cApplication Application = new cApplication();
    }
}

In my cApplications Class I have the following:

namespace App1_Name
{
    class cApplication
    {
        //Properties
        public string ApplicationName { get { return "App Name"; } }
    }
}

So in another class I am looking to use the class I instantiated on Form1 as so:

namespace App1_Name
{
    class cXML
    {
        public void Method1()
        {
            Console.WriteLine(Config.Application.ApplicationName);)
        }
     }
}

But I am getting an error that states "Config" doesn't exist in the current context, what am I doing wrong here?


Don't you miss instance of Form1?

Form1 form = new Form1();    
Console.WriteLine(form.Config.Application.ApplicationName);

because you are working with properties... not static classes and static methods.


I think you want this:

Console.WriteLine(Form1.Config.Application.ApplicationName);

EDIT: Dampe is correct; you need an instance of Form1, since Config is not a static member of the class. Please refer to his answer.


All of the above, or a one-liner:

Console.WriteLine(new Form1().Config.Application.ApplicationName);


Ok, in order to get my original code to work I made the cApplication Static. This is because I was instantiating the cXML in Form1's Form_Load event so the above solutions just created an endless loop.

What I did to resolve the issue was to pass the Config Class as a reference to the cXML class as follows:

namespace App1_Name
{
    public partial class Form1 : Form
    {
        public cConfig Config = new cConfig();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        cXML XML = new cXML();
        XML.Config = Config; //Passing the Config Class by Reference to cXML
    }
}

In the cXML class I am doing the following:

namespace App1_Name
{
    class cXML
    {
        public cConfig Config;

        public string AppName
        {

            Console.WriteLine(Config.Application.AppName);
        }
    }
}

This does exactly what I originally set out to do. My new question is is this an acceptable way of doing this?

0

精彩评论

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