Naw*_*waz 4 c# overloading dynamic overload-resolution
我正在编写一个序列化程序,我希望广泛使用方法重载,序列化派生类型的对象IEnumerable<T>,IDictionary<K,V>等等.
我还打算使用dynamic关键字让CLR根据要序列化的对象的运行时类型选择正确的重载.
看看这段代码:
void Serialize<TKey, TValue>(IDictionary<TKey, TValue> dictionary)
{
Console.WriteLine("IDictionary<TKey, TValue>");
}
void Serialize<TKey, TValue>(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
Console.WriteLine("IEnumerable<KeyValuePair<TKey, TValue>>");
}
void Serialize<T>(IEnumerable<T> items)
{
Console.WriteLine("IEnumerable<T>");
}
Run Code Online (Sandbox Code Playgroud)
我想这样做:
void CallSerialize(object obj)
{
Serialize(obj as dynamic); //let the CLR resolve it at runtime.
}
Run Code Online (Sandbox Code Playgroud)
现在基于运行时类型obj,将调用正确的重载.例如,
//Test code
CallSerialize(new List<int>()); //prints IEnumerable<T>
Run Code Online (Sandbox Code Playgroud)
在这种情况下,调用第三个重载并且基本原理非常简单:这只是可行的选项.
但是,如果我这样做:
CallSerialize(new Dictionary<int,int>()); //prints IDictionary<TKey, TValue>
Run Code Online (Sandbox Code Playgroud)
它调用第一个重载.我不太明白这一点.当所有三个过载都是可行的选项时,为什么它会解决第一个过载?
实际上,如果我删除第一个,则调用第二个重载,如果我删除第一个和第二个重载,则调用第三个重载.
解决方法重载的优先顺序是什么?
| 归档时间: |
|
| 查看次数: |
212 次 |
| 最近记录: |