实用技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > ASP.NET > 实用技巧 > .NET 扩展

.NET 扩展实现代码

作者:

增强.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");
}
}
阅读全文