gpt4 book ai didi

c# - 成员名称不能与其包含部分类的封闭类型相同

转载 作者:太空狗 更新时间:2023-10-29 22:19:40 25 4
gpt4 key购买 nike

我已经定义了一个具有如下属性的分部类:

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字典的内容。但是当我构建时我得到:

"member names cannot be the same as their enclosing type"

为什么?

最佳答案

索引器自动具有默认名称 Item - 这是您的包含类的名称。就 CLR 而言,索引器只是一个带有参数的属性,您不能声明与包含类同名的属性、方法等。

一个选项是重命名您的类,这样它就不会被称为 Item。另一种方法是通过 [IndexerNameAttribute] 更改用于索引器的“属性”的名称。 .

splinter 的较短示例:

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; } }
}

关于c# - 成员名称不能与其包含部分类的封闭类型相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13848287/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com