我刚刚开始,我有一个问题。我如何称呼公众无效?
e.g。
int x, y = 2;
namespace Blah
{
public class blah blah
{
public void count
{
Console.WriteLine("Hi: " + y);
}
public void counting
{
z = x * y
}
}
}
P.S:我试过这个How do I call a non-static method from a static method in C#?并且它对我不起作用
答案 0 :(得分:1)
如果它是非静态类,则需要先将其实例化。 然后调用它的void方法,justCallThem()。
public class blahblah
{
int x, y = 2; // this sets y as 2, but x is not set
public void count()
{
Console.WriteLine("Hi: " + y);
}
public void counting()
{
int z = x * y;
Console.WriteLine("Z = {0}", z);
}
}
class Program
{
static void Main(string[] args)
{
blahblah b = new blahblah(); //instantiate the object
b.count(); //call a method on the object
b.counting();
Console.ReadKey();
}
}
// output:
// Hi: 2
// z = 0
答案 1 :(得分:0)
您只需要通过类对象引用来调用该方法。
// Blah is a namespace
namespace Blah
{
// blah is the class name
public class blah
{
// x, y and z are member variables.
int x, y = 2;
int z = 0;
// SayHiis a public static method. Thus it dont requires the 'blah' object to call this method.
public static void SayHi()
{
Console.WriteLine("Hi: " + y);
}
// counting is a public non static method. Thus it requires the 'blah' object to call this method.
public void counting()
{
z = x * y;
}
}
}
// CallingMethod is the method where you want to call the counting method of class 'blah'
public void CallingMethod()
{
// As said above, you need a object to call the 'counting' method.
blah objBlah = new blah();
// Now call the non static method using this object.
objBlah.counting();
// and here you can directly call the non-static method SayHi like,
blah.SayHi();
}