小编lei*_*fre的帖子

C#将类型传递给要在"is"语句中进行求值的方法?

我想做类似下面列出的代码.基本上,我希望能够创建一个对象,但同时可选地提出一个接口要求

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)

但是对于泛型,接口要求不是可选的.我传递类型作为参数的第一个代码示例不能编译,我无法看到正确的语法.有没有人知道没有泛型的方法,所以我可以选择吗?

c# types interface

3
推荐指数
1
解决办法
1183
查看次数

标签 统计

c# ×1

interface ×1

types ×1