声明变量 - 最佳实践 [英] Declaring variables - best practices

查看:108
本文介绍了声明变量 - 最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了一个,而前(我想再次确认),如果你声明一个类级别的变量,你不应该调用它的构造,直到类的构造函数或负载被调用。原因是性能 - 但是否有其他原因做还是不做呢?有没有例外情况?

,即:这是我做的依据是什么,我认为最好的做法是:

 公共类SomeClass的
{
   私人PersonObject _person;

   公共SomeClass的()
   {
      _person =新PersonObject(Smitface);
   }
}
 

反对:

 公共类SomeClass的
{
   私人PersonObject _person =新PersonObject(Smitface);

   公共SomeClass的()
   {

   }
}
 

解决方案

如果你的构造函数之外设置可变那么就没有错误处理(HANDELING)提供。尽管在你的例子没什么区别,但也有很多情况下,你可能需要有某种形式的错误处理。在这种情况下,使用您的第一个选择是正确的。

NESCIO谈到了暗示这会对你的应用程序了,如果有一些构造失败。

由于这个原因,我总是用选项#1。

I found a while ago (and I want to confirm again) that if you declare a class level variable, you should not call its constructor until the class constructor or load has been called. The reason was performance - but are there other reasons to do or not do this? Are there exceptions to this rule?

ie: this is what I do based on what I think the best practice is:

public class SomeClass
{
   private PersonObject _person;

   public SomeClass()
   {
      _person = new PersonObject("Smitface");
   }
}

opposed to:

public class SomeClass
{
   private PersonObject _person = new PersonObject("Smitface");

   public SomeClass()
   {

   }
}

解决方案

If you set your variable outside of the constructor then there is no error handling (handeling) available. While in your example it makes no difference, but there are many cases that you may want to have some sort of error handling. In that case using your first option would be correct.

Nescio talked about what implication this would have on your applicaiton if there were some constructor failures.

For that reason, I always use Option #1.

这篇关于声明变量 - 最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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