英文:
new() usage in methods for C#
问题
给属性赋值new()
到底意味着什么呢?我发现一些例子中在方法调用中看到了new
的使用,但不像下面这样。
public ObservableCollection<Customer> Customers { get; } = new();
英文:
What exactly does it mean when assigning new()
to a property?
I found some examples of seeing new
usage in method calls but not like the below.
public ObservableCollection<Customer> Customers { get; } = new();
答案1
得分: 5
这是target-typed new
,实际上它将创建一个与操作数左侧的对象。
在自动属性的情况下,它将分配一个该属性类型的新实例给该属性。
所以,如果我们去掉所有的语法糖,你实际上得到的是:
private ObservableCollection<Customer> _customers = new ObservableCollection<Customer>();
public ObservableCollection<Customer> Customers
{
get
{
return _customers;
}
}
顺便说一下,几乎在任何已知类型存在的地方,都可以使用目标类型的 new
,不仅限于自动属性。
英文:
It's target-typed new
, essentially it will create an object of whatever the left of the operand is.
In the case of auto-properties, it will assign a new instance of the type of that property, to the property.
So if we strip away all of the syntactic sugar, what you've essentially got is:
private ObservableCollection<Customer> _customers = new ObservableCollection<Customer>();
public ObservableCollection<Customer> Customers
{
get
{
return _customers;
}
}
Incidentally, you can use a target-typed new
almost anywhere there's a well-known type, not just on auto-properties.
答案2
得分: 3
这是一个目标类型的new
表达式(在C# 9中引入),等同于:
public ObservableCollection<Customer> Customers { get; } = new ObservableCollection<Customer>();
所以Customers
是自动实现的属性,其初始化为新创建的ObservableCollection<Customer>
实例。
英文:
This is a target-typed new
expression (introduced in C# 9) and is equivalent to:
public ObservableCollection<Customer> Customers { get; } = new ObservableCollection<Customer>();
So the Customers
is an auto implemented property which initialized to a newly created instance of ObservableCollection<Customer>
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论