简体   繁体   English

我如何确定接口包含的类

[英]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.

相关问题 如何确定接口上哪个类称为公共方法? - How can I determine which class called a public method on an interface? 如何序列化包含接口的不可修改的类? - How do you serialize an unmodifiable class that contains an interface? 如何确定类与属性(抽象和接口)的关系 - How can I determine the relationship of a class to properties (Abstract and Interface) 如何以编程方式确定哪个WMI属性是类的主键? - How do I programmatically determine which WMI property is the primary key of a class? 如何使用反射确定已实现接口的通用类型? - How do I determine the generic type of an implemented interface using reflection? C#:如何确定接口变量的类型? - C#: how do I determine type of an interface variable? 如何将值添加到 class 类型 c 的列表中,该列表又包含 2 个其他类对象? - How do I add values to the list of a class type c which in turn contains 2 other classes objects? 如何模拟没有接口的类? - How do I mock a class without an interface? 我如何找到实现接口的类 - How do I find the class that implemented an interface 如何创建类的字典,以便我可以使用键来确定要初始化的新类? - How do I create a Dictionary of classes, so that I can use a key to determine which new class I want to initialize?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM