我们可以在不创建对象的情况下调用类的方法吗?为什么 [英] can we call a method of a class without creating object ? why

查看:183
本文介绍了我们可以在不创建对象的情况下调用类的方法吗?为什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Program 
{ 
    static void Main(string[] args) 
    { 
        new ShoppingCart().Process(); 
    } 
} 
 
class ShoppingCart 
{ 
    public void Process() 
    { 
        int magicDiscount = 5; 
        // ... 
    }
}





上面的代码我们调用方法

new ShoppingCart().Process();对此进行解释"





the above code we are calling the method

new ShoppingCart().Process();" explian about this"

推荐答案

如果您创建方法static,则它是Class方法,可以在以下位置调用班级,例如Int32.TryParse().所有其他方法都是实例类型,只能通过对象引用进行调用.
If you make a method static then it is a Class method and can be called on the class, e.g. Int32.TryParse(). All other methods are instance types and can only be called via an object reference.


Process方法可能应该是静态的.但是,正如其他人所说,您需要购买有关OO的书,而不是问我们.
The Process method should probably be static. But, as someone else said, you need to buy a book on OO, rather than asking us.


您正在创建ShoppingCart类的实例,然后在该实例上调用Process方法.如果您使用过静态修饰符,则不必创建ShoppingCart类的实例.
You are creating an instance of the ShoppingCart class and then calling the Process method on that instance. If you had used the static modifier, you would not have had to create the instance of the ShoppingCart class.


这篇关于我们可以在不创建对象的情况下调用类的方法吗?为什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆