【发布时间】:2009-04-03 03:27:32
【问题描述】:
我有一个泛型类,它接受两个类型参数Generic<A, B>。这个类的方法具有不同的签名,A 和 B 是不同的。但是,如果A == B 签名完全匹配,则无法执行重载解析。是否有可能以某种方式为这种情况指定方法的专业化?还是强制编译器任意选择匹配的重载之一?
using System;
namespace Test
{
class Generic<A, B>
{
public string Method(A a, B b)
{
return a.ToString() + b.ToString();
}
public string Method(B b, A a)
{
return b.ToString() + a.ToString();
}
}
class Program
{
static void Main(string[] args)
{
Generic<int, double> t1 = new Generic<int, double>();
Console.WriteLine(t1.Method(1.23, 1));
Generic<int, int> t2 = new Generic<int, int>();
// Following line gives:
// The call is ambiguous between the following methods
// or properties: 'Test.Generic<A,B>.Method(A, B)' and
// 'Test.Generic<A,B>.Method(B, A)'
Console.WriteLine(t2.Method(1, 2));
}
}
}
【问题讨论】:
标签: c# generics overloading