编程小知识之 C# indexer 和 property

栏目: ASP.NET · 发布时间: 7年前

内容简介:版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tkokof1/article/details/83661149

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tkokof1/article/details/83661149

本文简单介绍了混合使用 C# indexer 和 property 时可能出现的一种意外错误

C# 中的 property 想必大家都很熟悉,比起传统的 get 和 set 函数, property 的一大优势就是可以简化代码:

public class PropertyClass
{
	public string Item { get; set; }
}

不过 C# 中的 indexer 可能乍看上去就有些陌生了,基本的定义方法如下:

public class IndexerClass
{
    public object this[int index] { get { return null; } set {} }
}

这种定义方式对于偏于数组或者矩阵形式的数据类型特别有用,例如 Unity 中的 Matrix4x4 便定义了一个二维的indexer( Matrix4x4也定义了一维版本的indexer ),用以提供直观的数据访问方式:

// indexer of UnityEngine.Matrix4x4
public float this[int row, int column]
{
	get
	{
		return this[row + column * 4];
	}
	set
	{
		this[row + column * 4] = value;
	}
}

不过令人有些意外的是,如果我们混合使用上述的 indexer 和 property,竟然会导致编译错误:

// compile error ...
public class MixClass
{
	public string Item { get; set; }
	public object this[int index] { get { return null; } set {} }
}

原因在于 C# 使用了类似 property 的方式实现了 indexer,并且 indexer 所对应的 property 的变量名便是 “Item”, 所以上述代码会被编译器改写为以下形式( 不准确,仅作示意 ):

public class MixClass
{
	public string Item { get; set; }
	public object Item { get { return null; } set {} }
}

于是同名的 property 便造成了编译错误.

解决方法大概有两种,修改 property 的名字(不要以 “Item” 命名),或者修改 indexer 的名字,其中 indexer 名字的修改需要用到 属性 :

public class MixClass
{
	public string Item { get; set; }
	[System.Runtime.CompilerServices.IndexerName("IndexerItem")]
	public object this[int index] { get { return null; } set {} }
}
  1. class with indexer and property named “Item”
  2. item property in c#

以上所述就是小编给大家介绍的《编程小知识之 C# indexer 和 property》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

大话数据结构

大话数据结构

程杰 / 清华大学出版社 / 2011-6 / 59.00元

本书为超级畅销书《大话设计模式》作者程杰潜心三年推出的扛鼎之作!以一个计算机教师教学为场景,讲解数据结构和相关算法的知识。通篇以一种趣味方式来叙述,大量引用了各种各样的生活知识来类比,并充分运用图形语言来体现抽象内容,对数据结构所涉及到的一些经典算法做到逐行分析、多算法比较。与市场上的同类数据结构图书相比,本书内容趣味易读,算法讲解细致深刻,是一本非常适合自学的读物。 本书以一个计算机教师教......一起来看看 《大话数据结构》 这本书的介绍吧!

html转js在线工具
html转js在线工具

html转js在线工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具