在C#方法中使用new()

huangapple go评论66阅读模式
英文:

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&lt;Customer&gt; Customers { get; } = new ObservableCollection&lt;Customer&gt;();

So the Customers is an auto implemented property which initialized to a newly created instance of ObservableCollection&lt;Customer&gt;.

huangapple
  • 本文由 发表于 2023年2月8日 22:01:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/75386888.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定