简体   繁体   English

调用函数而不在C#中创建对象

[英]calling a function without creating object in C#

Is there any difference between these two cases in below program? 以下程序中的这两种情况有什么区别?

static void Main(string[] args)
{
     //Case 1:
     new Program().a();    

     //Case 2:
     Program p = new Program();
     p.a();
}

void a()
{
     // Do some stuff
}

In the first case you don't store you're Program object in a local variable. 在第一种情况下,您不会将Program对象存储在局部变量中。 The function is executed, but you can access your object that called the operation anymore. 该函数已执行,但是您可以再访问调用该操作的对象。

In the second case you store your object in a local variable and call again the method. 在第二种情况下,您将对象存储在局部变量中,然后再次调用该方法。 The method is executed and you could access the same object again later. 该方法已执行,您以后可以再次访问同一对象。

So it depends what you're going to do. 因此,这取决于您要做什么。 Concerning the executed method, there is no difference. 关于执行的方法,没有区别。 You have to think about if you need the Program object once more anywhere else in your code. 您必须考虑在代码中的其他任何地方是否再次需要Program对象。 Then you have to store it in a variable. 然后,您必须将其存储在变量中。 Otherwise you can do it like you did in your first case. 否则,您可以像在第一种情况下那样进行操作。

No. You're creating an object when you call new Program() . 不,您在调用new Program()时正在创建一个对象。 p is just a reference to that object, it adds almost nothing at all in terms of memory use or performances. p只是对该对象的引用,就内存使用或性能而言,它几乎没有添加任何内容。

In terms of style and readability of your code, it is advisable to avoid statements like new Program().a(); 就代码的样式和可读性而言,建议避免使用诸如new Program().a();类的语句new Program().a(); - It makes the code harder to debug because you can't place a brake-point on the statement you want and can't tell what caused an exception you may have caused. -这使代码更难调试,因为您不能在所需的语句上放置刹车点,也无法说出是什么原因导致了您可能引起的异常。
It is also not too clear what you're doing - you'd probably need to read that again to fully understand what is created , and what is executed and returned. 还不太清楚您在做什么-您可能需要再次阅读以完全了解创建了什么, 执行了什么并返回了什么。

No. (Other than that the latter may be very slightly more convenient for debugging.) 否。(除此之外,后者可能稍微更方便调试。)

I'm assuming here that the code above is all the code. 我在这里假设上面的代码就是所有代码。 Of course if you subsequently do something else with p then you've made a difference between the two :-). 当然,如果您随后p进行其他操作,那么您会在两者之间有所不同:-)。

There is just one difference (as you create a new object in both cases) - in the second one you can still access it by typing something like 仅有一个区别(两种情况下都创建一个新对象)-在第二种情况下,您仍然可以通过键入以下内容来访问它

p.AnotherMethod();

EDIT: 编辑:

If you don't want to create an object to invoke method "a", make this method static . 如果您不想创建一个对象来调用方法“ a”,请将此方法设置为static

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM