Skip to main content
 首页 » 编程设计

c#之C# 索引器是否返回变量或值

2024年02月13日16wuhuacong

可变结构容易出错; dictionary[0].Inflate(1,1)与 array[0].Inflate(1,1) 的行为不同什么时候T是一个矩形(因为 array[0] 是一个变量,而 dictionary[0] 是一个值)。

如果我为 SomeClass 创建自定义索引器:

public T this[int x, int y] { get { return arr[y*100+x]; } } 

是someclass[x,y] 变量 或值 还是两者都不是?假设T当然是 struct .

请您参考如下方法:

索引器访问表达式最初被归类为“索引器访问”。来自 C# 4 规范的第 7.6.6.2 节:

The result of processing the indexer access is an expression classified as an indexer access

然后从 7.1 节开始:

A property access or indexer access is always reclassified as a value by performing an invocation of the get-accessor or set-accessor.

所以基本上你可以认为它被归类为一个值。

但是,数组 访问被归类为变量表达式。来自 C# 4 规范的第 7.6.6.1 节:

The result of evaluating an array access is a variable of the element type of the array [...]

这就是为什么这样很好:

string[] x = { "", "", "" }; 
SomeMethodWithRef(ref x[0]); 

但这不是:

List<string> x = new List<string> { "", "", "" }; 
SomeMethodWitHRef(ref x[0]);