我定义了一个具有如下属性的分部类:
public partial class Item{
public string this[string key]
{
get
{
if (Fields == null) return null;
if (!Fields.ContainsKey(key))
{
var prop = GetType().GetProperty(key);
if (prop == null) return null;
return prop.GetValue(this, null) as string;
}
object value = Fields[key];
return value as string;
}
set
{
var property = GetType().GetProperty(key);
if (property == null)
{
Fields[key] = value;
}
else
{
property.SetValue(this, value, null);
}
}
}
}
这样我就可以做到:
myItem["key"];
并获取Fields字典的内容。但是当我构建时我得到:
“成员名称不能与其封闭类型相同”
Why?
索引器自动具有默认名称Item
- 这是您的包含类的名称。就 CLR 而言,索引器只是一个带有参数的属性,您不能声明与包含类同名的属性、方法等。
一种选择是重命名您的类,这样就不会调用它Item
。另一种方法是更改用于索引器的“属性”的名称,通过[IndexerNameAttribute].
破碎的较短示例:
class Item
{
public int this[int x] { get { return 0; } }
}
通过更改名称修复:
class Wibble
{
public int this[int x] { get { return 0; } }
}
或者按属性:
using System.Runtime.CompilerServices;
class Item
{
[IndexerName("Bob")]
public int this[int x] { get { return 0; } }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)