在C#中创建类实例的最佳方法是什么? [英] What is the best way to create a class instance in C#?

查看:99
本文介绍了在C#中创建类实例的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



以下语句之间有什么区别?

Public classname test = null;

classname test = new classname();

谢谢,
Giri

Hi,

What is the difference between the following statements?

Public classname test = null;

classname test = new classname();

Thanks,
Giri

推荐答案

第一个声明一个变量,该变量可以包含对类名"的引用.
第二个创建一个实际的类名",并在其上指向测试".

有点像通讯录:第一个语句在通讯簿中创建一个空白页,第二个语句填充详细信息.
The first declares a variable, which can hold a reference to a "classname".

The second creates an actual "classname" and points "test" at it.

It''s a bit like an address book: the first statement creates a blank page in the book, the second fills in the details.


我想你是说下面两个语句之间的区别:

I suppose you mean the difference between the two statements below:

classname test = null;

classname test = new classname();



-第一个将test变量设置为引用无". IE. test没有引用任何对象.

-第二个对象构造一个类型为classname的新对象,并将test变量设置为仅引用此新创建的对象.

:)



- The first one set the test variable to reference ''nothing''. I.e. test references no object.

- The second one constructs a new object of type classname and set the test variable to reference just this newly created object.

:)


1)公共类名test = null;

您已经包含了访问修饰符 [
2)classname test = new classname();

没有访问修饰符,因此将应用默认值.已使用默认构造将变量初始化为该类的新实例.
1) Public classname test = null;

You''ve included an access modifer[^] for the variable of public. The class has been set to ''null'' for it''s initial value, you''d still need to create an instance of the class at some point before you can use the variable

2) classname test = new classname();

No access modifer, so default will be applied. Variable has been initialised to a new instance of the class using the default construct.


这篇关于在C#中创建类实例的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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