【发布时间】:2021-06-08 09:41:41
【问题描述】:
如果我尝试在 C# 中定义以下 Pair<A, B> 类,则会出现编译器错误。
public class Pair<A, B>
{
public Pair(A a, B b)
{
this.A = a;
this.B = b;
}
public A A { get; }
public B B { get; }
}
编译错误是:
error CS0102: The type 'Pair<A, B>' already contains a definition for 'A' error CS0102: The type 'Pair<A, B>' already contains a definition for 'B'
冲突的定义在哪里?
通常,可以定义一个与其类型同名的属性,例如:
public Guid Guid { get; }
public Uri Uri { get; }
为什么编译器会抱怨名称 A 和 B?
【问题讨论】:
-
尽管问题来自泛型类型参数,而不是类型变量的命名冗余,但我推荐 C# Naming Conventions 和 C# Coding Standards and Naming Conventions 和 C# Coding Conventions (C# Programming Guide) 以及 Robert C. Martin 的书籍例如跨度>
-
“冲突的定义在哪里?” - 一个在类声明
Pair<A, B>中,一个用于属性。 (如果Guid是在同一个类中声明的嵌套类型,则您的Guid示例将被破坏,这更接近这里的情况。) -
@MarkSeemann:可以,而且类型参数的名称不允许与类成员的名称相同。
-
@JonSkeet 哇,我从 2002 年开始才编写 C#,但我并不知道。谢谢你的回答。这在 C# 规范中吗?
-
@MarkSeemann:是的,我正在添加一个链接。
标签: c# generics compiler-errors