如何知道一个接口的所有成员? [英] How to know all members of an interface?

查看:99
本文介绍了如何知道一个接口的所有成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实现接口时,我们必须知道要实现的所有成员(方法,索引等),而在编译时不会出现任何错误.但是我们怎么知道做得好呢?我们必须参考一些C#书,不是吗?如果是这样,请您在此处发布一些链接供我下载这些书,它们应该仅是界面"书.
非常感谢!
最好的问候!

When implementing an interface, we have to know all its members (methods, indexes, ...) to implement without getting any errors when compiling. But how can we know that to do well? We have to refer some C# book, don''t we? If so, could you please post some links here for me to download those books, they should be books of "interfaces" only.
Thank you so much!
Best Regards!

推荐答案

为什么?将接口添加到Visual Studio中的类时,可以将光标移动到接口名称中,该名称的左侧会出现一个小蓝框.将鼠标悬停在其上,将出现一个下拉列表,使您可以显式或隐式实现所有必需的方法.
Why? When you add an interface to a class in Visual Studio, you can move the cursor into the interface name, and a little blue box appears at the left hand side of the name. Hover the mouse over this, and a drop down will appear allowing you to explicitly or implicitly implement all required methods.


您将在未实现时找出它们的含义.它们在您的派生类中.
You''ll find out what they are when you haven''t implemented them in your derived class.


这并不是很难做到.

您需要使用System.Reflection.有关更多信息,请参见此命名空间.

这基本上就是您要做的:

This is not too hard to do.

You need to use System.Reflection. See this name space for more information.

Here is what you basically do:

Type interfaceType = typeof(IMyInterface);
System.Reflection.BindingFlags flags =
    System.Reflection.BindingFlags.Instance |
    System.Reflection.BindingFlags.Public |
    System.Reflection.BindingFlags.NonPublic; //very important, by default you would get only public
System.Reflection.PropertyInfo[] properties = interfaceType.GetProperties(flags);
System.Reflection.MethodInfo[] methods = interfaceType.GetMethods(flags);



作为进一步的步骤,您可以将所有属性访问器反映为方法,因为所有方法都反映参数及其类型等.

真正的问题是为什么?约翰是对的.
对于类或结构,这将是有意义的.在这种情况下,您可以构造对象并调用方法.接口没有意义.如果您具有实现此接口的结构或类,则只能实例化任何对象.如果您还反映了类或结构,那么我显示的代码可能会有些道理.

—SA



As some further step, you can reflect all properties accessors as methods, for all methods reflect parameters and their type and so on.

The real question is why? John is right.
It would makes sense for class or structure. In this case you could construct the object and invoke method. It make no sense for interface. You can only instantiate any object if you have structure or class implementing this interface. The code I show may make some sense if you also reflect a class or a structure.

—SA


这篇关于如何知道一个接口的所有成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆