C# C“将一个类型传递到一个方法中,该方法将在;是";陈述

C# C“将一个类型传递到一个方法中,该方法将在;是";陈述,c#,interface,types,C#,Interface,Types,我想做一些类似下面列出的代码的事情。基本上,我希望能够创建一个对象,但同时有选择地添加一个接口需求 public UserControl CreateObject(string objectName, Type InterfaceRequirement) { ///// create object code abbreviated here UserControl NewControl = createcontrol(objectName); if (Interf

我想做一些类似下面列出的代码的事情。基本上,我希望能够创建一个对象,但同时有选择地添加一个接口需求

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");

}
由于接口要求的问题,上述代码无法编译

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");

}
现在,我知道我可以用泛型实现这一点:

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");
}
public UserControl CreateObject(字符串objectName)
{
/////创建此处缩写的目标代码
UserControl NewControl=createcontrol(objectName);
if(NewControl是T)
返回新控件;
其他的
抛出新的SystemException(“请求的对象未实现所需的接口”);
}
但是对于泛型,接口需求不是可选的。我将类型作为参数传递的第一个代码示例没有编译,我看不出语法是否正确。有没有人知道在没有泛型的情况下如何实现这一点,以便我可以将其设置为可选的?

您可以检查
typeof(InterfaceRequirement)。可以从(type)
中识别

否则,可能
type.GetInterfaces()
并查找它


(其中
键入Type=NewControl.GetType();

必须对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");
}
public UserControl CreateObject(string objectName),其中T:class
{
/////创建此处缩写的目标代码
UserControl NewControl=createcontrol(objectName);
if(NewControl是T)
返回新控件;
其他的
抛出新的SystemException(“请求的对象未实现所需的接口”);
}

hth Mario

通用方法很好用,在这种情况下,如果需要的话,它确实可以强制工厂创建的子接口,但这是可选的,因此除非我想要一种通用和非通用方法,否则泛型并不是真正可行的方法您对代码做了一些调整:InterfaceRequest.IsAssignableFrom(NewControl.GetType());