【问题标题】:CS0102 The type 'A' already contains a definition for 'set_color'CS0102 类型“A”已包含“set_color”的定义
【发布时间】:2017-10-23 21:03:27
【问题描述】:

我在尝试编译通过 svcutil 生成的代理类时遇到了上述错误。这是问题的简短版本:

class A
{
    private string colorField;
    private string set_colorField; 

    public string color
    {
        get
        {
            return this.colorField;
        }
        set
        {
            this.colorField = value;
        }
    }

    public string set_color
    {
        get
        {
            return this.set_colorField;
        }
        set
        {
            this.set_colorField = value;
        }
    }
}

这编译得很好:

public string Color
{
    get;set;
}

public string Set_Color
{
    get;set;
}

但这会引发同样的错误:

public string color
{
    get;set;
}

public string set_color
{
    get;set;
}

我不记得曾经阅读过有关此限制的信息。有人可以指出 C# 编译器规范的相关部分吗?

【问题讨论】:

  • @Kirk 我明白这一点,但是 c# 编译器规范中提到此限制的相关部分在哪里?我找不到它:/

标签: c# .net


【解决方案1】:

https://github.com/dotnet/csharplang/blob/master/spec/classes.md#properties

为属性保留的成员名称

对于类型 T 的属性 P(Properties),以下签名是 保留:

T get_P();
void set_P(T value);

如果你有color 属性,set_color(...) 是保留的,这就是为什么你不能也有set_color 属性,因为它试图编译成相同的签名。

如果您拥有Color 属性,则为它保留set_Color(...),这就是Set_Color(注意大写字母)起作用的原因。

【讨论】:

  • 谢谢!我会尽快接受这个作为答案 - 必须等待 10 分钟。我在所有 Google 搜索中都找不到它。
  • 这就是为什么建议以大写字母开头的属性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-05
  • 2013-06-16
  • 1970-01-01
  • 2018-07-08
  • 1970-01-01
  • 1970-01-01
  • 2021-09-08
相关资源
最近更新 更多