从类中访问对象
我创建了一个名为 aNameClass.cs 的单独 .cs 文件,并在其中存储了以下类。 我可以在 Main() 语句中启动它,但是当我尝试访问 GetChoice 对象时,它告诉我由于权限无效而无法访问。
这是我启动它并访问它的代码。
namespace aNameCollector
{
// ...
csGetChoice gc = new csGetChoice();
choice = gc.GetChoice(); //invalid prividlidges???
class csGetChoice
{
static string GetChoice()
{
string choice = " ";
Console.WriteLine("++++++++++++++++++=A Name Collector+++++++++++++++");
Console.WriteLine();
Console.WriteLine("What would you like to do?");
Console.WriteLine("E = Enter a Name || D = Delete a Name || C = Clear Collector || V = View Collector || Q = Quit");
choice = Console.ReadLine();
return choice;
}
}
I have created a seperate .cs file names aNameClass.cs and have stored the following class in it.
I am able to iniatiate it in my Main() statment, but when I try to access the GetChoice object, it tells me it is inaccesable due to invalid prividlidges.
here is my code to iniatiate it and access it.
namespace aNameCollector
{
// ...
csGetChoice gc = new csGetChoice();
choice = gc.GetChoice(); //invalid prividlidges???
class csGetChoice
{
static string GetChoice()
{
string choice = " ";
Console.WriteLine("++++++++++++++++++=A Name Collector+++++++++++++++");
Console.WriteLine();
Console.WriteLine("What would you like to do?");
Console.WriteLine("E = Enter a Name || D = Delete a Name || C = Clear Collector || V = View Collector || Q = Quit");
choice = Console.ReadLine();
return choice;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要使用静态引用并为方法指定
public
,如下所示:或者使该方法成为实例方法而不是静态方法,并像这样定义和访问它:
如果您不提供 访问修饰符 默认为
private
因此仅对包含它的类可见,对任何其他类不可见。You need to use a static reference and specify
public
for the method like this:or make the method an instance method instead of static and define and access it like this:
If you don't provide an access modifier the default is
private
and therefore visible only to the class that contains it and not to any other classes.将方法设置为public,并在类型上而不是在实例上调用静态方法
Make the method public and call the static method on type not on the instance
类型成员的
static
关键字表明您可以通过直接引用类
而不是其对象。但是,您仍然需要正确的访问修饰符才能访问该成员。当您没有像您的情况那样在 C# 中显式声明访问修饰符时,
private
是默认值。这样您就可以仅在其类
内部访问该成员。为了能够从
类
外部访问它,您需要显式使用其他访问修饰符作为public
。The
static
key word for a type member states that you can access it by referencing theclass
directly and not its objects. However, you still need the right access modifier to be able to access that member.private
is the default value when you don't explicitly declare the access modifier in C# as in your case. And that allows you to access that member only inside itsclass
.To be able to access it from outside the
class
you need to explicitly use other access modifiers aspublic
.