我想做类似下面列出的代码。基本上,我希望能够创建一个对象,但同时可选地提出一个接口要求
public UserControl CreateObject(string objectName, Type InterfaceRequirement)
{
///// create object code abbreviated here
UserControl NewControl = createcontrol(objectName);
if (InterfaceRequirement == null || NewControl is InterfaceRequirement)
return NewControl;
else
throw new SystemException("Requested object does not implement required interface");
}
由于InterfaceRequirement
的问题,上述代码无法编译现在,我知道我可以用泛型来做到这一点:
public UserControl CreateObject<T>(string objectName)
{
///// create object code abbreviated here
UserControl NewControl = createcontrol(objectName);
if (NewControl is T)
return NewControl;
else
throw new SystemException("Requested object does not implement required interface");
}
但是使用泛型,接口要求不是可选的。我传递类型作为参数的第一个代码示例不能编译,我无法看到正确的语法。有没有人知道没有泛型的方法,所以我可以选择吗?
答案 0 :(得分:5)
您可以查看typeof(InterfaceRequirement).IsAssignableFrom(theType)
?
否则,也许theType.GetInterfaces()
并寻找它。
(Type theType = NewControl.GetType();
)
答案 1 :(得分:1)
你必须对T:
使用约束public UserControl CreateObject<T>(string objectName) where T : class
{
///// create object code abbreviated here
UserControl NewControl = createcontrol(objectName);
if (NewControl is T)
return NewControl;
else
throw new SystemException("Requested object does not implement required interface");
}
马里奥