前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >编程小知识之 C# indexer 和 property

编程小知识之 C# indexer 和 property

作者头像
用户2615200
发布2018-12-05 15:22:17
3890
发布2018-12-05 15:22:17
举报

版权声明:本文为博主原创文章,未经博主允许不得转载。

本文简单介绍了混合使用 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#
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018年11月02日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 参考
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档