-2
public static void callit(ref int var)  
{  
   var++;  
}  
public static void main(Object sender, EventArgs e)  
{  
   int num=6;  
   callit(ref num);  
   Console.WriteLine(num);  
}

但是如果这里的方法 callit() 不是静态的,那么我必须创建类的对象然后调用它。

4

9 回答 9

3

这是正确的。需要在对象的实例上调用非静态方法。即使该方法实际上没有使用对象的任何其他成员,编译器仍然会强制执行实例方法需要实例的规则。另一方面,静态方法不需要在实例上调用。这就是使它们成为静态的原因。

于 2011-05-26T16:38:01.267 回答
2

正是因为这就是静态方法的全部意义所在。

实例方法需要知道您调用该方法的类的哪个实例。

instance.Method();

然后他们可以引用类中的实例变量。

另一方面,静态方法不需要实例,但不能访问实例变量。

class.StaticMethod();

这方面的一个例子是:

public class ExampleClass
{
    public int InstanceNumber { get; set; }

    public static void HelpMe()
    {
        Console.WriteLine("I'm helping you.");
        // can't access InstanceNumber, which is an instance member, from a static method.
    }

    public int Work()
    {
        return InstanceNumber * 10;
    }
}

您可以创建此类的一个实例Work()来调用该特定实例上的方法

var example = new ExampleClass();
example.InstanceNumber = 100;
example.Work();

但是static,关键字意味着您不需要实例引用来调用该HelpMe()方法,因为它绑定到类,而不是类的特定实例

ExampleClass.HelpMe();
于 2011-05-26T16:39:22.850 回答
1

我认为MSDN解释得很好

Static classes and class members are used to create data and functions that can be accessed without creating an instance of the class. Static class members can be used to separate data and behavior that is independent of any object identity: the data and functions do not change regardless of what happens to the object. Static classes can be used when there is no data or behavior in the class that depends on object identity.

您可以在此处找到有关此主题的更多详细信息

于 2011-05-26T16:38:24.997 回答
1

如果我正确理解您的问题,这只是 C# 语法的问题。callit(ref num);在您的示例中使用没有歧义。确切地知道要调用什么方法,因为它是一个静态方法并且没有附加对象。另一方面,如果callit不是静态的,编译器将不知道调用该方法的对象,因为您是静态方法(没有对象)调用它。因此,您需要创建一个新对象并调用该对象的方法。

当然,如果这两个方法都不是静态的,则方法调用将对其自身进行操作,并且再次,对象将是已知的,因此没有问题。

于 2011-05-26T16:38:30.323 回答
0

因为静态方法与类本身相关联,而不是与特定对象实例相关联。

于 2011-05-26T16:37:26.120 回答
0

静态函数适用于类。成员函数适用于实例。

是的,您只能调用对象(实例)的成员函数。没有实例,没有成员。

于 2011-05-26T16:38:00.483 回答
0

静态方法在类型(或类)上调用,而非静态方法在类型的实例(即类的对象)上调用。

您不能在静态方法中调用非静态方法或非静态变量,因为可以有多个对象(即相同类型的实例)。

于 2011-05-26T16:40:34.543 回答
0

静态函数访问的类变量与任何其他静态函数和实例函数一样可访问。这意味着如果您有一个名为 的类变量static int count,在静态方法static increaseCount() { count++; }中将变量增加count1,在静态方法static decreaseCount() { count--; }中将变量count减少 1。

因此,静态函数和实例函数都可以访问静态变量,但静态函数不能访问实例变量。

静态函数也称为类函数。非静态函数也称为实例函数。

于 2011-05-26T16:42:32.523 回答
0

静态方法独立于实例,假设有 man 类,其中有非静态的 eat 方法和静态的 sleep 方法,那么当你创建不同的 man 实例时,可以说 man m1,m2。m1 和 m2 共享相同的 sleep 方法,但不同的 eat 方法。在java中,所有静态变量都存储在堆内存中,所有对象实例都共享,假设在运行时如果静态变量发生变化,那么它将在我们的case.m1和m2中的所有对象实例上共享。但是,如果您更改非静态变量,它将仅适用于该对象实例

m1.an 静态变量 = 1; // 改变 m2.anStaticvariable 的值但是 m1.nonStaticvariable = 1; //不会改变 m2.nonStaticvariable

希望这可以帮助你

于 2011-05-26T16:47:15.090 回答