【问题标题】:What does the following ambiguity errors mean?以下歧义错误是什么意思?
【发布时间】:2019-08-20 06:43:22
【问题描述】:

研究了这个错误,有些人说这是一个错误,但是当我使用他们的一些建议时,它并没有解决问题。我该怎么办?

**代码

/// Indicates if the profiles has been added.

public Boolean _isNew
{
    get { return _isNew; }
    set { _isNew = value; }
}

/// Indicates if any of the fields in the class have been modified

public Boolean _isDirty
{
    get { return _isDirty; }
    set { _isDirty = value; }
}


 //Gets and Sets delimiterChar 

         public Char _delimiterChar
     {
    get { return _delimiterChar; }
    set  { _delimiterChar = value;}

    }

错误**

Ambiguity between 'ConsoleApplication3.ProfileClass.isNew'and 'ConsoleApplication3.ProfileClass.isNew

Ambiguity between 'ConsoleApplication3.ProfileClass.isDirty'and 'ConsoleApplication3.ProfileClass.isDirty

Ambiguity between 'ConsoleApplication3.ProfileClass._delimiterChar'and 'ConsoleApplication3.ProfileClass._delimiterChar

【问题讨论】:

  • 似乎您已经为某些属性提供了与其支持字段相同的名称。他们必须不同。传统上,字段名称以下划线开头并采用驼峰式,而属性名称将采用不带前缀的 PascalCase。

标签: c#


【解决方案1】:

您发布的代码将导致递归并最终导致堆栈溢出。您正在尝试在属性设置器中设置属性。您需要一个支持字段或自动属性来实现您正在做的事情。比如:

private bool _isNew;
public Boolean IsNew
{
    get { return _isNew; }
    set { _isNew = value; }
}

public Boolean IsNew {get; set;}

【讨论】:

    【解决方案2】:

    在 C# 中,如果指定要获取和设置的内容,则不能使用与属性相同的名称(自引用问题)。截至目前,您正在尝试获取并设置其自身的属性,这是无效的。还要注意命名约定,您的公共属性不应以下划线开头,而应遵循大写的驼峰式大小写。

    对此有两个答案,这两个答案都同样有效,具体取决于您需要做什么。

    方法 1:如果取出它正在获取和设置的内容,C# 可以找出 IsNew 属性引用的隐含字段。这本质上是方法 2 的简写。

    public bool IsNew { get; set; } // shorthand way of creating a property
    

    方法 2:指定要获取和设置的字段。

    private bool  _isNew; // the field
    public bool IsNew { get => _isNew; set => _isNew = value; } // this is the property controlling access to _isNew
    

    在此处阅读更多信息:Shorthand Accessors and Mutators

    本质上,如果您不需要执行任何其他操作,则默认使用方法 1。但是,如果您需要在获取或设置时提供附加功能,请使用方法 2(即查找 MVVM 模式以获取示例 https://www.c-sharpcorner.com/UploadFile/raj1979/simple-mvvm-pattern-in-wpf/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-30
      • 2015-03-04
      • 2012-11-26
      相关资源
      最近更新 更多