C# 类不公开
我正在尝试创建一个类,因此当我在文件中执行以下操作时:
Functions LoginFunctions = new Functions();
LoginFunctions.loadFunctions();
它将创建我需要的对象,并将其公开,以便每个调用该类的表单都能够使用它。类文件如下。
namespace App
{
public class Functions
{
public void loadFunctions()
{
TaskbarItemInfo taskbarItemInfo = new TaskbarItemInfo();
}
}
}
它似乎没有将 taskbarItemInfo 对象公开,并且不允许我在类内部以外的其他任何地方使用它。如何将其公开,以便调用该类的每个文件都可以使用该对象?
I am trying to make a class so when I do the following inside a file:
Functions LoginFunctions = new Functions();
LoginFunctions.loadFunctions();
It will create my object which I need, and make it public so every form which calls the class will be able to use it. The class file is below.
namespace App
{
public class Functions
{
public void loadFunctions()
{
TaskbarItemInfo taskbarItemInfo = new TaskbarItemInfo();
}
}
}
It doesn't seem to be making the taskbarItemInfo object public, and it is not letting me use it anywhere else other then inside the class. How do I make it public so every file that calls the class can use the object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
正如其他人提到的,将其设为属性,例如如下所示:
As the others have mentioned, make it a property, for example like so:
您的 taskbaritem 类在该方法的范围内,因此您将无法在该类之外访问它。
创建一个公共属性或在方法中返回它。
我还将去将 loadFunctions 方法更改为构造函数,该构造函数创建您需要的所有对象。
Your taskbaritem class is in the scope of the method and therefore you wont be able to access it outsite of the class.
Create a public property or return it in the method.
I would also go and change the loadFunctions method to a constructor which creates all the objects you need.
在您提供的示例中,
taskbarItemInfo
是在loadFunctions()
方法的本地范围内声明的。如果您希望它对某个类公开,则必须先使其成为类成员,然后才能将其公开。In the example you provide,
taskbarItemInfo
is declared within the local scope of theloadFunctions()
method. If you want it to be public for some class, you must make it a class member before you can make it public.您需要将变量公开。
编辑:您还可以在构造函数中对项目进行初始化。
那么在初始化 LoginFunctions 对象后,您就不需要
LoginFunctions.loadFunctions();
行代码。You need to make the variable public.
EDIT: You could also do the initialization of the items in the constructor.
Then you don't need the
LoginFunctions.loadFunctions();
line of code after you initialize your LoginFunctions object.您可能希望将其作为属性来访问,以便在需要时生成私有静态成员。
You probably want to access it as a property which generates a private static member when needed.