[英]how do i determine which class an interface contains
i have a set of classes that belong to an interface; 我有一组属于接口的类;
public class Platform : IGraphic
{
}
public class Decal : IGraphic
{
}
public class Character : IGraphic
{
}
public interface IGraphic
{
}
If i set an IGraphic value to point to say Decal like so; 如果我设置一个IGraphic值来像这样说Decal;
IGraphic graphic = new Decal();
How can i, at some later point, determine which Class the Interface has been set to? 稍后,我如何确定接口设置为哪个类?
您可以使用以下方法确定接口的实现:
graphic.GetType()
First, classes do not belong to an interface, they can implement it. 首先,类不属于接口,它们可以实现它。 Now, after we have defined it you can see that implementing the interface enables you to know that such methods are implemented in each class that implements the interface. 现在,在定义好接口之后,您可以看到实现接口使您知道在实现接口的每个类中都实现了此类方法。 So your question is kind of backwards, you can implement the method differently for each class so you won't have to know what is the type of your object. 因此,您的问题有点倒退,可以为每个类分别实现不同的方法,因此您不必知道对象的类型是什么。
If you insist knowing the type you can use reflection. 如果您坚持知道类型,则可以使用反射。 I advice you using reflection as less as you can. 我建议您尽量少使用反射。 If you wan't to describe the purpose of your program maybe we can help you avoiding reflection (usually- a better architecture) 如果您不想描述程序的目的,也许我们可以帮助您避免反思(通常是更好的体系结构)
Use graphic.GetType()
. 使用graphic.GetType()
。
This will get the Type
of the instance. 这将获取实例的Type
。
Note that this works for every kind of object, not just for interfaces. 请注意,这适用于各种对象,而不仅适用于接口。
You could conceivably also use 您可以想象也可以使用
if (graphic is Platform)
or 要么
if (graphic is Decal)
etc. 等等
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.