我们可以在不创建对象的情况下调用类的方法吗?为什么
问题描述:
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 methodstatic
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.