为什么我不能在另一个类中调用公共方法? [英] Why can't I call a public method in another class?
问题描述
我让这两个类相互作用,并且我试图从第一类中调用四个不同的类以用于第二类.
I have got these two classes interacting and I am trying to call four different classes from class one for use in class two.
这些方法是公共的,并且它们确实返回值,但是由于某种原因,没有建立连接.
我尝试时遇到的错误是:"An object reference is required for the nonstatic field, method, or property 'GradeBook.[method I want called]'"
The methods are public and they do return values but for some reason there is not a connection being made.
The error I get when I try is: "An object reference is required for the nonstatic field, method, or property 'GradeBook.[method I want called]'"
我已初始化所有内容.我不想将这些方法创建为静态方法.我再次阅读了作业的详细信息,我什至不应该这样做,但我似乎无法做到这一点.
I have everything initialized. I don't want to create the methods as static. I read over the specifics of my assignment again and I'm not even supposed to but I can't seem to get this to work anyway I word it.
myGradeBook.[方法] GraceBook.[方法]
myGradeBook.[method] GraceBook.[method]
这一切似乎都产生了错误.
It all seems to create errors.
当前错误:
The best overloaded method match or 'System.Console.WriteLine(string, object)' has some invalid arguments.
Arugment '2': cannot convert from 'method group' to 'object'
我什至不明白那些意思....
I'm not even sur what those mean....
我只是通过Visual Studio的逐步进入"功能解决了该问题. 我不知道为什么要花这么长时间才能使用它.
I just fixed that problem thanks to the Step Into feature of Visual Studio. I don't know why it took me so long to use it.
推荐答案
您正试图在该类上调用实例方法.要在类上调用实例方法,必须创建一个在其上调用该方法的实例.如果要在非实例上调用该方法,请添加static关键字.例如
You're trying to call an instance method on the class. To call an instance method on a class you must create an instance on which to call the method. If you want to call the method on non-instances add the static keyword. For example
class Example {
public static string NonInstanceMethod() {
return "static";
}
public string InstanceMethod() {
return "non-static";
}
}
static void SomeMethod() {
Console.WriteLine(Example.NonInstanceMethod());
Console.WriteLine(Example.InstanceMethod()); // Does not compile
Example v1 = new Example();
Console.WriteLine(v1.InstanceMethod());
}
这篇关于为什么我不能在另一个类中调用公共方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!