首页 > 解决方案 > C# Object Intantiation 格式问题声明变量与不声明变量

问题描述

我是 C# 的新手,我想我看到了两种不同的方法来做同样的事情,或者我只是不理解。我的“Murach 的 C# 2015”书在第 369 页上有一个创建 2 个对象实例的示例,如下所示:

Product product1, product2;
product1 = new Product("something", "something else", more stuff);
product2 = new Product("something different", "something else different", more different stuff);

你也可以这样做吗?

Product product1 = new Product("something", "something else", more stuff);
Product product2 = new Product("something different", "something else different", more different stuff);

似乎某些在线资源以一种方式进行,而其他资源以另一种方式进行,或者就像我说的那样......也许我只是错过了一些东西。

标签: c#objectinstancenew-operatorinstantiation

解决方案


您必须在使用之前声明变量(一次),但您可以多次分配声明的对象变量。

// declare the variable
Product product1 
// assign to first product
product1 = new Product("first product");
// assign to a different product
product1 = new Product("second product");

您可以使用声明和分配作为“速记”的技术,因此您可以合并前两行代码(不包括注释):

//declare and assign the variable in one step
Product product1 = new Product("first product");
//re-assign the previously declared variable to a different object
product1 = new Product("second product");

你只声明一次变量,所以这会给你一个错误:

Product product1 = new Product("first product");
Product product1 = new Product("second product");

推荐阅读