假设这样:
public class GenericMethods
{
public T Method<T>() where T : struct
{
// Do something specific to a struct
}
public T Method<T>() where T : class
{
// Do something specific to a class
}
}
在编译时不知何故无效,因为这两个方法采用相同的参数。但是,由于约束是相互排斥的,这两种方法真的会发生冲突吗?会不会在解析T的时候,软件无法选择这两种方法中的一种?
如果泛型类型是结构体或类,那么如何创建两个具有相同名称和参数的泛型方法?
最佳答案
没有。不考虑约束。返回类型也不是。这不会编译,并且不是合法的 C#。
这记录在 C# 语言规范的 3.6 中:
The signature of a method specifically does not include the return type, the params modifier that may be specified for the right-most parameter, nor the optional type parameter constraints.
虽然这两种方法在“逻辑上”是不同的,并且不会冲突,因为约束应该清楚地表明调用的是哪一种,但 C# 语言不支持这一点。语言设计者决定,这就是他们为 C# 实现规则所选择的方式。
关于c# - 解析通用方法签名时是否考虑了约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13143834/