Why does the VS Metadata view does not display explicit interface implemented members

泄露秘密 提交于 2019-11-28 13:39:33

The reason is that those methods are there just to implement the I-interface and not to augment the class' public interface.

What I mean is that if you have the following:

public class MyClass : IConvertible
{
 // implementation
}

You might want MyClass to be convertible, indeed, so you can pass references of it to methods that expect IConvertible:

public void DoSomethingWithConvertible(IConvertible conv)

But you might not want variables of type MyClass to expose the Convert methods. You simply don't want MyClass's public interface to have that method, then you implement the interface explicitly. That's the whole idea of the approach. This means the following is not allowed:

MyClass a = new MyClass();
a.Convert();

However, the following is still be allowed:

MyClass a = new MyClass();
((IConvertible)a).Convert();

The whole idea behind this is that even though we're using the exact same instance, a as MyClass doesn't have the method. A as IConvertible does have the method. Think of it as if you're allowing the instance to have split personality.

Usually I end implementing every interface implicitly. However, there are very specific situations where I'd implementing them explicitly exactly for the reasons outlined above.

BTW, thanks for the great question!

Because explicit interface implementation actually hides the implementation.

The metadata does indeed show the explicitly implemented. Do you mean intellisense and not metadata?

I'd say that's by design and help the developer of say Boolean to restrict the interface to a subset. By restricting what's suggested to use it also becomes visible what's considered abnormal usage. E.g. it's generally not advised to view a Boolean value as a specific numeric value but in certain cases it's handy to be able to do that anyways.

IDictinary<T,K> is another example. It implements IEnumerable<KeyValuePair<T,K>> making it possible to iterate over all the pairs in the collection and ICollation<KeyValuePair<T,K>>. So you can call Add on the dictionary given a KeyValuePair but usually you should use Add(K, key, T Value)

Try inspecting the class with a tool that provides read access to metadata. ILDASM for one and you can indeed find metadata of the explicitly implemented methods.

They are explicitly implemented. You can find all implemented convertables here: http://msdn.microsoft.com/en-us/library/system.boolean.aspx

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