简体   繁体   English

使用和不使用构造函数声明 C# 变量

[英]Declaring C# variable with and without Constructor

I have this doubt in my mind for a very long time.我心中有这个疑问很久了。 May be this is the right forum to ask..可能这是提问的正确论坛..

Is there any difference between the two types of variable declaration in C#. C#中两种类型的变量声明有什么区别吗? If so what is the difference and which is the best practice.如果是这样,有什么区别,哪个是最佳实践。

  DataTable dt;

vs对比

  DataTable dt=new Datatable();

First one you are only declaring and in second you declaring and initializing.第一个你只是声明,第二个你声明和初始化。 If you use any instance of a class without initializing, then you will get null reference exception as Object reference not set to an instance of an object如果您在未初始化的情况下使用类的任何实例,那么您将获得null引用异常,因为Object reference not set to an instance of an objectObject reference not set to an instance of an object

http://msdn.microsoft.com/en-us/library/ms173109.aspx http://msdn.microsoft.com/en-us/library/ms173109.aspx

if DataTable is a struct they are the same如果 DataTable 是一个结构,它们是相同的

if not DataTable dt;如果不是DataTable dt; means create empy reference to a DataTable named dt;表示创建对名为 dt 的DataTable empy 引用; 'new Datatable();' '新数据表();' means init the reference using Datatable object from the garbage collector意味着使用来自垃圾收集器的Datatable对象初始化引用

In my opinion the best practice is to always initialize the variable in the constructor and never in the declaration.在我看来,最好的做法是始终在构造函数中初始化变量,而不要在声明中初始化。 This is for consistency mainly, if you want to see how a type is initialized you should always only have to look in the constructor.这主要是为了一致性,如果您想查看类型是如何初始化的,您应该始终只需要查看构造函数。

The first dt can hold a DataTable or object that inherites DataTable , the value of the first dt will be null after the first one is done.第一个 dt 可以保存一个 DataTable 或继承DataTable对象,第一个 dt 完成后第一个 dt 的值将为null

The second dt can hold a DataTable or object that inherites DataTable, You initiated it with empty constructor of DataTable therefore it will not be null .第二个 dt 可以保存一个DataTable或继承 DataTable 的对象,您使用DataTable空构造函数启动它,因此它不会为null

"Best Parctice" is depends on what you want to do with dt. “Best Parctice”取决于你想用 dt 做什么。 for example, if you have a method on the next line that returns a new initiated DataTable it is not nessesery to initiate an instance that will not be used.例如,如果您在下一行有一个返回新启动的DataTable那么启动一个不会被使用的实例是不必要的。

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

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