泛型类型已经包含定义
The generic type already contains a definition
如果我尝试在 C# 中定义以下 Pair<A, B>
class,我会收到编译器错误。
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# 标准的“Class 成员”部分中指定。在当前draft-v6 branch:
The name of a type parameter in the type_parameter_list of a class declaration shall differ from the names of all other type parameters in the same type_parameter_list and shall differ from the name of the class and the names of all members of the class.
换句话说,您无法获得与另一个类型参数或 class 成员同名的类型参数。在这里,您有一个名为 A
的类型参数和一个名为 A
.
的 属性
属性 的类型也是 A
的事实无关紧要;此代码给出相同的错误:
class Broken<T>
{
public string T { get; set; }
}
如果我尝试在 C# 中定义以下 Pair<A, B>
class,我会收到编译器错误。
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# 标准的“Class 成员”部分中指定。在当前draft-v6 branch:
The name of a type parameter in the type_parameter_list of a class declaration shall differ from the names of all other type parameters in the same type_parameter_list and shall differ from the name of the class and the names of all members of the class.
换句话说,您无法获得与另一个类型参数或 class 成员同名的类型参数。在这里,您有一个名为 A
的类型参数和一个名为 A
.
属性 的类型也是 A
的事实无关紧要;此代码给出相同的错误:
class Broken<T>
{
public string T { get; set; }
}