首页 / C# / 在C#中解决方法重载的优先规则是什么?
在C#中解决方法重载的优先规则是什么?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了在C#中解决方法重载的优先规则是什么?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1880字,纯文字阅读大概需要3分钟。
内容图文
![在C#中解决方法重载的优先规则是什么?](/upload/InfoBanner/zyjiaocheng/816/98af5d3994b54e15b435023c7205cf3a.jpg)
我正在编写一个序列化器,其中我想广泛地利用方法重载,来序列化从IEnumerable< T>,IDictionary< K,V>派生的类型的对象.等等.
我还打算使用dynamic关键字让C??LR根据要序列化的对象的运行时类型选择正确的重载.
看看这段代码:
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>");
}
我想这样做:
void CallSerialize(object obj)
{
Serialize(obj as dynamic); //let the CLR resolve it at runtime.
}
现在基于obj的运行时类型,将调用正确的重载.例如,
//Test code
CallSerialize(new List<int>()); //prints IEnumerable<T>
在这种情况下,调用第三个重载并且基本原理非常简单:这只是可行的选项.
但是,如果我这样做:
CallSerialize(new Dictionary<int,int>()); //prints IDictionary<TKey, TValue>
它调用第一个重载.我不太明白这一点.当所有三个过载都是可行的选项时,为什么它会解决第一个过载?
实际上,如果我删除第一个,则调用第二个重载,如果我删除第一个和第二个重载,则调用第三个重载.
解决方法重载的优先顺序是什么?
解决方法:
解决方法重载的规则将尝试选择具有最特定类型匹配的方法头. Here你可以阅读更多关于重载分辨率和here我认为是你的情况.
来自MSDN:
Given an argument list A with a set of argument types {A1, A2, …, AN} and two applicable function members MP and MQ with parameter types {P1, P2, …, PN} and {Q1, Q2, …, QN}, MP is defined to be a better function member than MQ if
for each argument, the implicit conversion from AX to PX is not worse than the implicit conversion from AX to QX, and
for at least one argument, the conversion from AX to PX is better than the conversion from >AX to QX.
When performing this evaluation, if MP or MQ is applicable in its expanded form, then PX or QX refers to a parameter in the expanded form of the parameter list.
内容总结
以上是互联网集市为您收集整理的在C#中解决方法重载的优先规则是什么?全部内容,希望文章能够帮你解决在C#中解决方法重载的优先规则是什么?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。