Is there a better alternative than this to 'switch on type'?

后端 未结 30 3025
梦毁少年i
梦毁少年i 2020-11-22 03:28

Seeing as C# can\'t switch on a Type (which I gather wasn\'t added as a special case because is relationships mean that more than one distinct

30条回答
  •  清歌不尽
    2020-11-22 03:56

    If you know the class you are expecting but you still don't have an object you can even do this:

    private string GetAcceptButtonText() where T : BaseClass, new()
    {
        switch (new T())
        {
            case BaseClassReview _: return "Review";
            case BaseClassValidate _: return "Validate";
            case BaseClassAcknowledge _: return "Acknowledge";
            default: return "Accept";
        }
    }
    

提交回复
热议问题