在这个情况下:
// We have an interface...
interface InterfaceB {}
// And this class implements the interface.
class ImplementsB : InterfaceB {}
// But this class does not.
class DoesNotImplementB {}
你可以定义MethodA
为:
static Type MethodA<TClass, TInterface>()
where TClass : TInterface
{
return typeof(TClass);
}
然后以下将起作用:
Type t = MethodA<ImplementsB, InterfaceB>();
但这会产生编译时错误:
Type t = MethodA<DoesNotImplementB, InterfaceB>();
类型“DoesNotImplementB”不能用作泛型类型或方法“MethodA<TClass,TInterface>()”中的类型参数“TClass”。没有从“DoesNotImplementB”到“InterfaceB”的隐式引用转换。
因此,通过这种方式,您可以确定 的结果MethodA
是一个Type
实现TInterface
. 给定该Type
对象,您可以稍后像这样实例化它:
public object Instantiate(Type type)
{
// Call the default constructor.
// You can change this to call any constructor you want.
var constructor = type.GetConstructor(Type.EmptyTypes);
var instance = constructor.Invoke(new object[0]);
return instance;
}
如果您知道您Type
的接口与某些接口兼容TInterface
,那么您可以使用这样的附加方法来避免强制转换:
public TInterface Instantiate<TInterface>(Type type)
{
return (TInterface)Instantiate(type);
}
但是,如果type
是 aType
以某种方式无法实现TInterface
,您将InvalidCastException
在运行时得到 a 。没有办法限制Type
为在编译时实现特定接口的类型。但是,在运行时您可以检查它以避免InvalidCastException
异常:
public TInterface Instantiate<TInterface>(Type type)
{
if (!typeof(TInterface).IsAssignableFrom(type))
throw new Exception("Wrong type!");
return (TInterface)Instantiate(type);
}
请注意,这typeof(TType)
是一个生成Type
对象的表达式,因此在您看到的任何地方都typeof()
可以用任何Type
变量替换它,反之亦然。
这是你想知道的吗?