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

|
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()不是静态的,那么我必须使类成为对象,然后调用它。     
已邀请:
没错。需要在对象的实例上调用非静态方法。即使该方法实际上并未使用该对象的任何其他成员,编译器仍会强制执行实例方法要求实例的规则。另一方面,静态方法不需要在实例上调用。这就是使它们静止的原因。     
正是因为这就是静态方法的重点。 实例方法需要知道您在其上调用该方法的类的哪个实例。
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();
    
我认为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.
您可以在此处找到有关此主题的更多详细信息     
如果我正确理解了您的问题,这只是C#语法问题。在示例中使用using10毫无疑问。确切知道要调用什么方法,因为它是静态方法并且没有附加对象。另一方面,如果
callit
不是静态的,则编译器将不知道在其上调用该方法的对象,因为您是从静态方法(无对象)调用它的。因此,您将需要创建一个新对象并在该对象上调用方法。 当然,如果两个方法都不是静态的,则该方法调用将对自身进行操作,并且该对象将是已知的,因此没有问题。     
因为静态方法与类本身相关联,而不与特定的对象实例相关联。     
静态函数对类起作用。 成员函数适用于实例。 是的,您只能调用对象(实例)的成员函数。没有实例,没有成员。     
在类型(或类)上调用静态方法,而在类型的实例(即类的对象)上调用非静态方法。 您不能在静态方法中调用非静态方法或非静态变量,因为可能存在多个对象(即同一类型的实例)。     
静态函数访问类变量,其他任何静态函数和实例函数都可以访问这些类变量。这意味着如果您有一个名为
static int count
的类变量,则在静态方法
static increaseCount() { count++; }
中将变量
count
增加1,而在静态方法
static decreaseCount() { count--; }
中将变量
count
减少1。 因此,静态函数和实例函数都可以访问静态变量,但是静态函数不能访问实例变量。 静态函数也称为类函数。 非静态函数也称为实例函数。     
静态方法与实例无关,假设存在man类,即存在非静态的eat方法和静态的sleep方法,那么当您创建不同的man实例时,可以说man m1,m2。 m1和m2共享相同的睡眠方式,但饮食方式不同。在Java中,所有静态变量都存储在堆内存中,所有对象实例都在运行时共享,如果静态变量发生更改,则它将在我们的case.m1和m2中在对象的所有实例上共享。但是,如果您更改非静态变量,则仅适用于该对象实例 m1.anStaticvariable = 1; //同时更改m2.anStaticvariable的值 但 m1.nonStaticvariable = 1; //不会更改m2.nonStaticvariable 希望这对您有帮助     

要回复问题请先登录注册