Check if 'T' inherits or implements a class/interface

后端 未结 8 1820
名媛妹妹
名媛妹妹 2020-12-08 04:00

Is there a way to test if T inherits/implements a class/interface?

private void MyGenericClass ()
{
    if(T ... inherits or implements some class/i         


        
8条回答
  •  我在风中等你
    2020-12-08 04:06

    If you want to check during compilation: Error if if T does NOT implement the desired interface/class, you can use the following constraint

    public void MyRestrictedMethod() where T : MyInterface1, MyInterface2, MySuperClass
    {
        //Code of my method here, clean without any check for type constraints.
    }
    

    I hope that helps.

提交回复
热议问题