我想做类似下面列出的代码.基本上,我希望能够创建一个对象,但同时可选地提出一个接口要求
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");
}
Run Code Online (Sandbox Code Playgroud)
由于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");
}
Run Code Online (Sandbox Code Playgroud)
但是对于泛型,接口要求不是可选的.我传递类型作为参数的第一个代码示例不能编译,我无法看到正确的语法.有没有人知道没有泛型的方法,所以我可以选择吗?