Asking a Generic Method to Throw Specific Exception Type on FAIL

前端 未结 5 980
深忆病人
深忆病人 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:02

    I think seeing as all exceptions should have a parameterless constructor, and have the Message property, so the following should work:

    static ExType TestException(string message) where ExType:Exception
    {
        ExType ex = new ExType();
        ex.Message = message;
        return ex;
    }
    

    Edit: OK, Message is read only, so you'll have to hope the class implements the Exception(string) constructor instead.

    static ExType TestException(string message) where ExType:Exception
    {
        return new ExType(message);
    }
    

提交回复
热议问题