我在这个简单的例子中很难理解为什么没有选择正确的重载。在查看C# 5规范中的7.5.3.2 Better function member后,似乎应该能够选择非泛型重载,但是我不理解
object
参数在某种程度上如何影响决策。我的问题是,我无法调用非泛型版本的Foo(object)
而不将参数强制转换为object
。根据错误提示,似乎不支持这样做,我希望有人能解释一下原因。public class A
{
public string Type { get { return "non-generic"; } }
}
public class A<T>
{
public string Type { get { return "generic"; } }
}
class Program
{
// (In reality only one of the variants below can be uncommented.)
static void Main(string[] args)
{
// This works fine and calls the generic overload as expected
A<string> x = Foo<string>("foobar");
// This results in a compile time error
// CS0029: Cannot implicitly convert type 'A<string>' to 'A'
A x = Foo("foobar");
// This works, but ends up calling the generic overload
var x = Foo("foobar");
// This works fine and calls the non-generic overload as expected
object a = "foobar";
var x = Foo(a);
// This works fine and calls the non-generic overload as expected
A x = Foo((object)"foobar");
// By using dynamic we're able to get rid of the compile-time error, but get a
// runtime exception.
// RuntimeBinderException: Cannot implicitly convert type 'A<string>' to 'A'
A x = Foo((dynamic)"foobar");
Console.WriteLine(x.Type);
Console.ReadLine();
}
private static A Foo(object x)
{
return new A();
}
private static A<T> Foo<T>(T x)
{
return new A<T>();
}
}