C # Pass a type to a method that should be evaluated in an "is" statement?

I want to do something like the code below. Basically, I want to be able to create an object, but at the same time, perhaps put requirements on the 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");

}

The above code does not compile due to problems with InterfaceRequirement

Now, I know that I can do this with generics:

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

but with generics, an interface requirement is optional. The first code example in which I pass the type as a parameter does not compile, and I do not see the syntax being correct. Does anyone know a way to do this without generics so that I can make it optional?

+3
source share
2 answers

Can you check typeof(InterfaceRequirement).IsAssignableFrom(theType)?

, , theType.GetInterfaces() .

( Type theType = NewControl.GetType();)

+5

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

hth Mario

+1

Source: https://habr.com/ru/post/1785357/


All Articles