Asking a Generic Method to Throw Specific Exception Type on FAIL

前端 未结 5 984
深忆病人
深忆病人 2021-02-08 06:32

Right, I know I am totally going to look an idiot with this one, but my brain is just not kicking in to gear this morning.

I want to have a method where I can sa

5条回答
  •  醉酒成梦
    2021-02-08 07:09

    The only issue with the solution is that it is possible to create a subclass of Exception which does not implement a constructor with a single string parameter, so the MethodMissingException might be thrown.

    static void TestException(string message) where E : Exception, new()
    {
        try 
        {
          return Activator.CreateInstance(typeof(E), message) as E;
        } 
        catch(MissingMethodException ex) 
        {
          return new E();
        }
    }
    

提交回复
热议问题