Skip to main content
 首页 » 编程设计

c#之编译器错误 CS0542 : member names cannot be the same as their enclosing type 的解决方法

2024年02月20日11kerrycode

我有一个相当大的 VB.NET 项目,它是由一位前雇员构建的。他使大部分工作正常,但不是全部。

它已经这样运行了 2 年,我知道。可能是 3 个。

现在,管理层正在努力让这个项目恢复并完成从未完成的工作。

项目已分配给我,我有一个月的时间来加快速度。

我正在用 C# 重写它,因为我的编码在该语言中更强大。

他使用的一个好主意是构建类,以便它们模仿数据库表:

  • 表名变成类名
  • 列名成为属性名
  • 列数据类型成为属性数据类型

这是一个小例子:

Public Class Acct_Code 
    Private _Acct_Code_ID As String = String.Empty 
    Private _Acct_Code As String = String.Empty 
 
    Public Property Acct_Code_ID() As String 
        Get 
            Return _Acct_Code_ID 
        End Get 
        Set(ByVal value As String) 
            _Acct_Code_ID = value 
        End Set 
    End Property 
 
    Public Property Acct_Code() As String 
        Get 
            Return _Acct_Code 
        End Get 
        Set(ByVal value As String) 
            _Acct_Code = value 
        End Set 
    End Property 
 
End Class 

目前,由于 Error CS0542,我无法将此 VB 代码放入 C# 中上面写着:

Error Message
'user-defined type' : member names cannot be the same as their enclosing type
A name was used more than once in the same construct. This error might be caused by inadvertently putting a return type on a constructor.

我理解应该重命名类或属性;但是,我希望一次让这个项目工作,而不是在这里创建根本无法工作的代码。

有谁知道解决此编译器错误的方法 - 只是在我构建项目之前暂时解决?

我知道有一些方法可以忽略警告和异常,但我不知道有什么方法可以忽略编译器错误。

请您参考如下方法:

要解决编译器错误,只需将您的类拆分为一个基类和一个派生类,然后将有问题的成员移动到基类中。

class A 
{ 
    public string B { get; set; } // <-- This compiles just right! 
} 
 
class B : A 
{ 
}