C#对象实例化格式问题声明变量与不声明变量[已关闭]。

问题描述 投票:0回答:2

我是C#新手,我想我看到了2种不同的方法来做同样的事情,或者我只是没有理解。我的 "Murach's 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# object instance new-operator instantiation
2个回答
1
投票

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

// 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");

1
投票

第一部分

当你需要在作用域外访问你的变量时,第一种风格是首选,比如说,如果你只需要在if条件内实例化你的对象,而你也需要在if条件外访问对象,那么你会这样做。


Product product1;

if(condition == true)
{
    product1 = new Product("something", "something else", more stuff);
}

product1.isInitiated = true 

在这里,只有第一种初始化类型可以工作,因为我们需要在if条件之外访问它。

第二部分

现在,如果你只需要在if循环中访问属性,那么第二种方法也会工作,比如说

if(condition == true)
{
    Product product1 = new Product("something", "something else", more stuff);
    product1.isInitiated = true 
}


在这种情况下,你可以选择在同一个点进行实例化和初始化,或者在if循环中进行实例化和初始化。

© www.soinside.com 2019 - 2024. All rights reserved.