选择哪种C#方法重载? [英] Which C# method overload is chosen?

查看:78
本文介绍了选择哪种C#方法重载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public static void method1(object obj)$ b $为什么在两个重载匹配时调用泛型方法? b {
Console.WriteLine(Object);


public static void method1< T>(T t)
{
Console.WriteLine(Type T);


public static void Main(String args [])
{
method1(xyz); //将打印Type T;
}

这里不应该有任何冲突,对吗?

解决方案

通过选择最具体的过载来解决重载问题。在这种情况下, method1< string>(string) method1(object)更具体, C#规范第7.4.2节。

如果你想选择一个特定的重载,你可以通过明确地转换参数到你想要的类型。以下将调用 method1(object)重载,而不是通用的:

 方法1((对象) XYZ); 

在某些情况下,编译器无法知道要选择哪个超载,例如:

  void method2(string x,object y); 
void method2(object x,string y);

method2(xyz,abc);

在这种情况下,编译器不知道选择哪个超载,因为过载显然比另一个(它不知道哪个字符串隐式向下对象)。所以它会发出编译器错误。


Why is the generic method called when both overloads would match?

public static void method1(object obj)
{
    Console.WriteLine("Object");
}

public static void method1<T>(T t)
{
    Console.WriteLine("Type T");
}

public static void Main(String args[])
{
    method1("xyz"); //Will print "Type T";
}

There should not be any conflicts here, right?

解决方案

Overloads are resolved by choosing the most specific overload. In this case, method1<string>(string) is more specific than method1(object) so that is the overload chosen.

There are details in section 7.4.2 of the C# specification.

If you want to select a specific overload, you can do so by explicitly casting the parameters to the types that you want. The following will call the method1(object) overload instead of the generic one:

method1((object)"xyz"); 

There are cases where the compiler won't know which overload to select, for example:

void method2(string x, object y);
void method2(object x, string y);

method2("xyz", "abc");

In this case the compiler doesn't know which overload to pick, because neither overload is clearly better than the other (it doesn't know which string to implicitly downcast to object). So it will emit a compiler error.

这篇关于选择哪种C#方法重载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆