在另一个类中使用实例化的类
请原谅我的无知,我正在从 VB6 过渡到 C#(非常陡峭的学习曲线)。我已经用谷歌搜索了这个,但我无法弄清楚这一点。我在我的主窗体上实例化了一个类:
namespace App1_Name
{
public partial class Form1 : Form
{
public cConfig Config = new cConfig();
}
}
在我的 Config 类中,我正在实例化另外两个类:
namespace App1_Name
{
class cConfig
{
//Properties
public cApplication Application = new cApplication();
}
}
在我的 cApplications 类中,我有以下内容:
namespace App1_Name
{
class cApplication
{
//Properties
public string ApplicationName { get { return "App Name"; } }
}
}
因此,在另一个类中,我希望使用在 Form1 上实例化的类:
namespace App1_Name
{
class cXML
{
public void Method1()
{
Console.WriteLine(Config.Application.ApplicationName);)
}
}
}
但我是收到一条错误,指出当前上下文中不存在“Config”,我在这里做错了什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您是否错过了 Form1 的实例?
因为您正在使用属性...而不是静态类和静态方法。
Don't you miss instance of Form1?
because you are working with properties... not static classes and static methods.
我想你想要这个:
编辑:Dampe是正确的;您需要 Form1 的实例,因为 Config 不是该类的静态成员。请参考他的回答。
I think you want this:
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:
好吧,为了让我的原始代码正常工作,我将 cApplication 设为静态。这是因为我在 Form1 的 Form_Load 事件中实例化 cXML,因此上述解决方案只是创建了一个无限循环。
我为解决该问题所做的是将 Config 类作为对 cXML 类的引用传递,如下所示:
在 cXML 类中,我正在执行以下操作:
这正是我最初打算做的事情。我的新问题是这是一种可以接受的方式吗?
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:
In the cXML class I am doing the following:
This does exactly what I originally set out to do. My new question is is this an acceptable way of doing this?