c# - 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);
似乎某些在线资源以一种方式进行,而其他资源以另一种方式进行,或者就像我说的那样......也许我只是错过了一些东西。
解决方案
您必须在使用之前声明变量(一次),但您可以多次分配声明的对象变量。
// 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");
推荐阅读
- rust - Rust 中相同类型的相同 trait 的多个实现
- android - addNotificationReceivedListener 在使用 expo-notifications 时未在 expo 中收到通知反应本机
- android - 引起:java.lang.AssertionError: 无法删除缓存目录 yourProject\build\kotlin\compileDebugTestingKotlin
- python - Python,BeautifulSoup:在解析 HTML 表时,只返回一个 CSV 行或不断收到“AttributeError:'NoneType' object has no attribute 'text'”
- sql - WHERE 语句的数量是否会影响查询性能?
- r - 如何在 PERMANOVA(素食主义者)中包含随机效应?
- r - ifelse() 使用 mutate 无法正常工作:R
- c# - 该模板使用了尚不支持 UWp 的 shell
- excel - 在多个单元格/工作表上一次更新 excel 公式
- javascript - 如何从电子中的渲染器进程调用 preload.js 中定义的函数