问题描述
我的问题是:为什么从未调用 AddData(string data)
?当我调用 ds.Add("Some text")
时, data
参数的类型在编译时是已知的,因此 Add
的重载实现应该调用 AddData(string)
方法(或者这就是我所希望的)
My question is: Why is AddData(string data)
never called? When I call ds.Add("Some text")
then the type of data
parameter is known at compilation time thus the overloaded implementation of Add
should call AddData(string)
method (or this is what I was hoped for)
输出为
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);
}
}
}
推荐答案
在代码编译时会发生重载解析.
Overload resolution happens at compile time for your code.
在编译时,编译器不知道 T
的实际含义,因此此调用:
At compile time, the compiler has no knowledge of what T
actually is, so this call:
public void Add<T>(T data)
{
AddData(data); <------
}
根据重载解析规则.
一种在运行时解决过载的方法是使公共 Add
接受一个 dynamic
参数:
One way to make overload resolution happen at runtime is to make the public Add
accept a dynamic
parameter:
// you should change the interface declaration also!
public void Add(dynamic data)
{
AddData(data);
}
这将产生输出:
Accept string data
Ignore data of type System.Double
这篇关于从泛型方法调用重载的泛型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!