简体   繁体   English

为什么这是多余的?

[英]Why is this cast redundant?

I have a method with the following overloads: 我有以下重载的方法:

string Call(string function, Dictionary<string, object> parameters, object body)
string Call(string function, Dictionary<string, object> parameters, JObject body)

Now I added another overload: 现在,我添加了另一个重载:

string Call(string function)
{
    return Call(function, null, (JObject) null);
}

I added a cast to JObject so the compiler knows which overload it should use. 我向JObject添加了JObject以便编译器知道应使用哪个重载。 But Visual Studio tells me that the cast is redundant. 但是Visual Studio告诉我,转换是多余的。 But why isn't my call ambiguous without the cast? 但是,如果没有演员阵容,为什么我的通话不会模棱两可?

But why isn't my call ambiguous without the cast? 但是,如果没有演员阵容,为什么我的通话不会模棱两可?

Because the overload with the JObject parameter is "better" than the overload with the object parameter... because the conversion from null to JObject is "better" than the conversion from null to object . 因为JObject参数的重载比object参数的重载更好……因为从nullJObject的转换比从nullobject的转换“更好”。

JObject is more specific than object , because there's an implicit conversion from JObject to object , but not vice versa. JObjectobject更具体,因为从JObjectobject存在隐式转换,反之亦然。

If the final parameter for the first method were string instead (for example) then neither overload would be better than the other, and the call would be ambiguous without the cast. 如果第一个方法的最终参数是string (例如),则这两个重载都不会比另一个重载好,并且如果不进行强制转换,则调用是模棱两可的。

See section 7.5.3 of the C# 5 specification for all the intricate details. 有关所有复杂细节,请参见C#5规范的7.5.3节。 In particular, section 7.5.3.5 ("better conversion target") is relevant here. 特别是在这里,第7.5.3.5节(“更好的转换目标”)很重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Visual Studio 2015表示'演员是多余的'。为什么? - Visual Studio 2015 says the 'cast is redundant'. Why? 为什么即使VS说它是多余的,这个演员会改变结果? - Why does this cast change the result when even VS says it is redundant? 尝试强制转换为通用类型时出错:冗余强制转换 - Error trying to cast to generic type: redundant cast 为什么根据ReSharper将double-to-int强制转换分配给动态变量是多余的? - Why is double-to-int cast being assigned to a dynamic variable redundant according to ReSharper? 返回否定的布尔值时,“ Cast是多余的”警告 - “Cast is redundant” warning when returning negated bool 为什么需要冗余锁定对象? - Why is a redundant lock object needed? 使用反射传递参数时,Visual Studio强制转换是多余的 - Visual studio cast is redundant when passing arguments using reflection Visual Studio 2015:插值字符串表达式中的“Cast is redundant”警告无效 - Visual Studio 2015: Invalid “Cast is redundant” warning in interpolated string expression “数组初始化程序中的冗余逗号”为什么应该修复它 - “redundant comma in array initializer” why it should be fixed C#:为什么第一个命名空间是多余的? - C# : Why is First namespace redundant?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM