.NET 扩展

class Command
{
    public virtual void Execute() { }
}

class InvalidOperationException<T> : InvalidOperationException
    where T : Command
{
    public InvalidOperationException(string message) : base(message) { }
    // some specific information about
    // the command type T that threw this exception
}

static class CommandExtensions
{
    public static void ThrowInvalidOperationException<TCommand>(
        this TCommand command, string message) 
        where TCommand : Command
    {
        throw new InvalidOperationException<TCommand>(message);
    }
}

class CopyCommand : Command
{
    public override void Execute()
    {
        // after something went wrong:
        this.ThrowInvalidOperationException("Something went wrong");
    }
}

class CutCommand : Command
{
    public override void Execute()
    {
        // after something went wrong:
        this.ThrowInvalidOperationException("Something else went wrong");
    }
}

2 comments

  1. Gale Wernli 说道:

    I just want to mention I am all new to blogs and seriously liked you’re web page. Likely I’m likely to bookmark your blog post . You definitely have outstanding stories. Thanks a lot for sharing with us your web page.

  2. Dorinda Kinch 说道:

    Would you be considering exchanging links?

发表评论

电子邮件地址不会被公开。