在这种情况下:
// 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>();
The type 'DoesNotImplementB' cannot be used as type parameter 'TClass' in the generic type or method 'MethodA<TClass,TInterface>()'. There is no implicit reference conversion from 'DoesNotImplementB' to 'InterfaceB'.
所以,这样你肯定的MethodA
结果是实现TInterface
类的Type
。鉴于Type
对象,你可以instantate它以后是这样的:
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
是Type
某种程度上不执行TInterface
,您将在运行时得到一个InvalidCastException
。没有办法将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
变量,反之亦然。
这是你想知道的吗?
将返回类型更改为'TInterface' – asawyer 2012-07-25 22:21:17
您是使用“Type”来表示“System.Type”,还是意味着您已经定义了某种类型?在前一种情况下,由于显而易见的原因,你试图做的事情是不可能的,而且你几乎肯定不应该从'System.Type'派生出来。 – 2012-07-25 22:30:53
是的,我的意思是System.Type。我试图看看是否可以获得实现TInterface的类定义,其中稍后我将对其进行“新增”处理。我试图避免在这个特殊的方法中使用新的方法。 – Eric 2012-07-26 14:10:57