Why does .Net Framework base types do not contain implementations of IConvertible methods?

筅森魡賤 提交于 2019-12-10 15:14:20

问题


.Net Framework base types such as Int32, Int64, Boolean etc,. implement IConvertible interface but the metadata of these types do not contain the implementations of the methods defined in IConvertible interface such as ToByte, ToBoolean etc,.

I am trying to understand why the base types do not have the method implementations even though they implements IConvertible interface. Could anyone please help on this?


回答1:


Take a closer look at the documentation - Int32 implements IConvertible explicitly.

When a class/struct implements an interface explicitly, you have to cast instances of that type to its interface before calling those methods

var asConvertable = (IConvertible) 3; //boxing
var someByte = asConvertible.ToByte();



回答2:


Int32 and other primitive types implement the IConvertible interface explicitly. Explicit interface implementation means that the method doesn't appear in the concrete's type public methods: you can't call it directly, you need to cast to the interface first.

int x = 42;
IConvertible c = (IConvertible)x;
byte b = c.ToByte();

To implement an interface explicitly, you don't specify an accessibility level, and you prefix the method name with the interface name:

byte IConvertible.ToByte()
{
    ...
}

To access the method with reflection, you must include the full name of the interface:

MethodInfo toByte =
    typeof(int).GetMethod("System.IConvertible.ToByte",
                          BindingFlags.Instance | BindingFlags.NonPublic);


来源:https://stackoverflow.com/questions/27096112/why-does-net-framework-base-types-do-not-contain-implementations-of-iconvertibl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!