[英]Accessing extension methods via generics always matches the least specific option?
当直接访问新的扩展方法时,此方法很好用(在下面的示例中,前三个写操作),但是当实例首先传递给通用方法时,则所选的扩展方法始终是对象的扩展方法(后三个写操作) )。
我是在做错什么,还是C#编译器的局限性?
public class Call { public string Number { get; set; } }
public class Message { public string Address { get; set; } }
public class Unknown { }
public static class Extensions
{
public static string ID(this object item) { return "Unknown"; }
public static string ID(this Call item) { return item.Number; }
public static string ID(this Message item) { return item.Address; }
}
internal class Program
{
private static void Main()
{
var call = new Call { Number = "555-1212" };
var msg = new Message { Address = "you@email.com" };
var other = new Unknown();
// These work just as I would expect
// - printing out Number, Address, or the default
System.Console.WriteLine("Call = {0}", call.ID());
System.Console.WriteLine("Message = {0}", msg.ID());
System.Console.WriteLine("Unknown = {0}", other.ID());
System.Console.WriteLine();
// These all print out "Unknown"
System.Console.WriteLine("Call = {0}", GetID(call));
System.Console.WriteLine("Message = {0}", GetID(msg));
System.Console.WriteLine("Unknown = {0}", GetID(other));
}
public static string GetID<T>(T item)
{
return item.ID();
}
}
重载解析在编译时执行。 编译器对T
一无所知,因此唯一适用的重载就是这个:
public static string ID(this object item) { return "Unknown"; }
如果要在执行时有效地执行重载解析,并且使用的是C#4,则可能要考虑使用dynamic
-不幸的是,它不直接支持扩展方法:
public static string GetID(dynamic item)
{
return Extensions.ID(item);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.