C# Pass a type into method to be evaluated in an "is" statement?
I want to do something like the code listed below. Basically, I want to be able to create an object but at the same time optionally put on an interface requirement
public UserControl CreateObject(string objectName, Type InterfaceRequirement)
{
///// create object code abbreviated here
UserControl NewControl = createcontrol(objectName);
if (InterfaceRequirement == null || NewControl is InterfaceRequirement)
return NewCo开发者_JS百科ntrol;
else
throw new SystemException("Requested object does not implement required interface");
}
The above code does not compile due to issues with InterfaceRequirement
now, I know 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 the generics, the interface requirement is not optional. The first code example where I am passing type as a parameter does not compile and I cant see to get the syntax right. Does anyone know a way to do this without generics so i can make it optional?
You can check typeof(InterfaceRequirement).IsAssignableFrom(theType)
?
Otherwise, maybe theType.GetInterfaces()
and look for it.
(where Type theType = NewControl.GetType();
)
You have to use a constraint for 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
精彩评论