我需要这个,以便当我创建类型的实例时,编译器会知道该类型实现了 IInterface。
下面我将向您展示两种可能的方法来获取实现IInterface 的那些类的type 列表。所以在创建新对象时,你可以使用这个列表来决定这个类是否实现了IInterfce。
如果你想要一个编译时解决方案,你应该有一个 List<IInterface> ,那么这个列表中只允许那些实现 IInterface 的类的对象。有了这个列表(只有那些实现IInterface 的类的对象后,使用这个列表来准备类型的列表。
例如。
Demo 类实现了 IInterface 而Demo2 没有。
List<IInterface> listOfIInterface = new List<IInterface>();
listOfIInterface.Add(new Demo());
listOfIInterface.Add(new Demo2()); //this line will have compile time error
现在使用这个列表来准备类型的列表
List<Type> listOfIInterfaceType = new List<Type>();
foreach(object obj in listOfIInterface)
{
listOfIInterfaceType.Add(obj.GetType());
}
如果您想为您的问题提供更多动态和运行时的解决方案,请试试这个。
如果有多个类并且您想知道哪个类实现了IInterface 并将这些类的类型选择到一个列表中。你可以试试下面的代码。
假设有两个类Demo 和Demo2。 Demo 确实实现了 IInterface 而 Demo2 没有。
当你拥有两个类的对象时,你将它们放入Object 的列表中并在该列表上循环并执行以下逻辑。
List<object> listOfObject = new List<object>();
listOfObject.Add(new Demo()); //Demo Implements IInterface
listOfObject.Add(new Demo2());//Demo2 doesn't Implement IInterface
//this will have all possible types
List<Type> listOfAllType = new List<Type>();
//this will have type of those class, which implement interface
List<Type> listOfInterfaceType = new List<Type>();
//this will have objet of those class, which implement interface.
List<object> listOfInterfaceObject = new List<object>();
foreach (object obj in listOfObject)
{
Type type = obj.GetType();
if (!listOfAllType.Contains(type))
listOfAllType.Add(obj.GetType());
IInterface testInstance = obj as IInterface;
if (testInstance != null)
{
if (!listOfInterfaceType.Contains(type))
listOfInterfaceType.Add(type);
if (!listOfInterfaceObject.Contains(obj))
listOfInterfaceObject.Add(obj);
}
}
请注意,如果任何类没有实现接口,则它的对象不能转换为接口。因此,如果testInstance 在尝试转换后仍然为空,则它的类没有实现接口。