Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

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

The other day i was looking at C# Boolean struct metadata.

Boolean implements the interface IConvertible. But looking at Boolean's members i could not see most of the IConvertible members.

I've done some tests with some colleagues, including creating our own classes, and came to the conclusion that IConvertible must be implemented explicitly for Boolean.

The question is, why are they not visible? I understand it might be a 'by design decision' but i understand that it would add greater value if they were visible to anyone inspecting the metadata.

The tests were done in VS2010 .NET4.0

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...