Item 和 this[] - 同名成员已声明
可能的重复:
具有索引器和名为“Item”的属性的类
刚刚遇到了一些我以前没见过,想知道为什么会发生这种情况?
对于以下类,我收到关于“Item”和“this[...]”的编译器错误“已声明具有相同名称的成员”。
public class SomeClass : IDataErrorInfo
{
public int Item { get; set; }
public string this[string propertyName]
{
get
{
if (propertyName == "Item" && Item <= 0)
{
return "Item must be greater than 0";
}
return null;
}
}
public string Error
{
get { return null; }
}
}
编译器似乎认为 this[...] 和 Item 使用相同的成员名称。这是正确/正常的吗?我很惊讶我以前没有遇到过这个。
Possible Duplicate:
Class with indexer and property named “Item”
Just came across something I've not seen before and was wondering why this might be happening?
With the following class, I get the compiler error "Member with the same name is already declared" with respect to "Item" and "this[...]".
public class SomeClass : IDataErrorInfo
{
public int Item { get; set; }
public string this[string propertyName]
{
get
{
if (propertyName == "Item" && Item <= 0)
{
return "Item must be greater than 0";
}
return null;
}
}
public string Error
{
get { return null; }
}
}
The compiler seems to think that this[...] and Item are using the same member name. Is this correct / normal? I am surprised I have not come across this before.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当您像这样定义索引器时:
它被编译到
.Item
属性中。您可以使用索引器的
[System.Runtime.CompilerServices.IndexerName("NEW NAME FOR YOUR PROPERTY")]
属性来修复此问题。When you define the indexer like this:
It is compiled into the
.Item
property.You can fix that with
[System.Runtime.CompilerServices.IndexerName("NEW NAME FOR YOUR PROPERTY")]
attribute to your indexer.是的。
this[]
默认情况下编译为名为Item
的属性。您可以使用 System.Runtime.CompilerServices.IndexerName 属性进行更改。 (MSDN 链接)Yep.
this[]
compiles down to a property calledItem
by default. You can change that using theSystem.Runtime.CompilerServices.IndexerName
attribute. (MSDN link)这很正常。 C# 语言有关键字“this”,用于声明索引器,但在编译后的类中,索引器的 get 方法将称为“get_Item”(这是.NET 中的跨语言约定)。由于编译器希望为 Item 属性的 getter 提供相同的名称,因此会报告错误。
It's normal. The C# language has the keyword "this" which is used to declare indexers, but in the compiled class, the get method for the indexer will be called "get_Item" (which is the cross-language convention in .NET). Since the compiler wants to give the same name to the getter for your Item property, it reports an error.
如果您使用 IL 代码查看 IDataErrorInfo 接口,您会发现
它在 C# 中确实翻译为
So ,原因是 C# 确实在 this 语法后面隐藏了一些特殊的方法名称,这确实与 CLR 使用的真实方法名称发生冲突。
If you look at the IDataErrorInfo interface with IL code you will se
which does translate in C# to
So the reason is C# does hide some special method name behind the this syntax from you which does collide with the real method name used by the CLR.