【问题标题】:C# Pass a type into method to be evaluated in an "is" statement?C#将类型传递给要在“is”语句中评估的方法?
【发布时间】:2011-06-08 23:19:42
【问题描述】:

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

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

但是对于泛型,接口要求不是可选的。我将类型作为参数传递的第一个代码示例无法编译,并且我看不到正确的语法。有谁知道没有泛型的方法,所以我可以让它成为可选的?

【问题讨论】:

    标签: c# interface types


    【解决方案1】:

    您可以查看typeof(InterfaceRequirement).IsAssignableFrom(theType)?

    否则,也许theType.GetInterfaces() 并寻找它。

    (其中Type theType = NewControl.GetType();)

    【讨论】:

    • 对代码稍作调整是对的:InterfaceRequirement.IsAssignableFrom(NewControl.GetType());
    【解决方案2】:

    你必须对 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");
    }
    

    第一个马里奥

    【讨论】:

    • 泛型工作正常,在这种情况下,如果需要,它确实可以强制创建工厂的子接口,但这是可选的,所以泛型并不是真正的方法,除非我想要一个泛型和非泛型方法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-08
    • 1970-01-01
    • 2013-01-09
    • 1970-01-01
    • 2012-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多