为什么我们不需要通过对象调用静态方法?

时间:2011-05-26 16:34:44

标签: c# static class-method

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()不是静态的那么我必须创建类的对象然后调用它。

9 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分: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()方法,因为它绑定到类,而不是特定实例 of class

ExampleClass.HelpMe();

答案 2 :(得分: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.

您可以在here

找到有关此主题的更多详细信息

答案 3 :(得分:1)

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

当然,如果这两种方法都不是静态的,那么方法调用就会自行运行,而且对象也是已知的,所以没有问题。

答案 4 :(得分:0)

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

答案 5 :(得分:0)

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

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

答案 6 :(得分:0)

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

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

答案 7 :(得分:0)

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

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

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

答案 8 :(得分:0)

静态方法独立于实例,假设有man类,其中有非静态的eat方法,并且有静态的sleep方法然后当你创建man的不同实例时让我说m1,m2。 m1和m2共享相同的睡眠方法但不同的吃法。在java中,所有静态变量都存储在堆内存中,如果静态变量发生变化则会在运行时共享所有对象实例,然后它将在我们的case.m1和m2中共享对象的所有实例。但是如果你改变非静态变量,它只会用于那个对象实例

m1.anStaticvariable = 1; //也改变m2.anStatic变量的值 但 m1.nonStaticvariable = 1; //不会改变m2.nonStaticvariable

希望这有助于你