我的问题是:为什么从未叫过AddData(string data)
?当我调用ds.Add("Some text")
时,在编译时就知道data
参数的类型,因此Add
的重载实现应调用AddData(string)
方法(或者这是我所希望的)]
输出为
Ignore data of type System.String
Ignore data of type System.Double
using System;
namespace GenericCall
{
interface IDataStore
{
void Add<T>(T data);
}
class MyDataStore : IDataStore
{
public void Add<T>(T data)
{
AddData(data);
}
private void AddData<T>(T data)
{
Console.WriteLine($"Ignore data of type {data.GetType()}");
}
private void AddData(string data)
{
Console.WriteLine("Accept string data");
}
}
class Program
{
static void Main(string[] args)
{
MyDataStore ds = new MyDataStore();
ds.Add("Some text");
ds.Add(3.14);
}
}
}
超载解析在编译时发生。
在编译时,编译器不知道T
实际上是什么,因此此调用:
public void Add<T>(T data)
{
AddData(data); <------
}
可以只能解析为通用的Add
。
使过载解析在运行时发生的一种方法是使公共Add
接受dynamic
参数:
// you should change the interface declaration also!
public void Add(dynamic data)
{
AddData(data);
}
这将产生输出:
Accept string data
Ignore data of type System.Double