c# - 拦截泛型类中的方法调用

标签 c# generics

我有这个代码:

abstract class CommunicationChannel<Client> : IDisposable where Client :  class, IDisposable {
    protected Client client;

    public void Open() {
        try
        {
            client = CreateClient();
        }
        catch (Exception)
        {
            client.Dispose();
            throw;
        }
    }

    public virtual void  Dispose() {
        client.Dispose();
    }

    private Client CreateClient()
    {
        return Activator.CreateInstance<Client>();
    }
}

class Communicator : CommunicationChannel<Client>
{
    // here I have specific methods
    void Method1(args) {
        Open();

        try {
            client.Method1(args);
        }
        catch(Exception) {
            // Cleanup
        }
    }

    // this is getting too verbose already
    void Method2(args) {
        Open();

        try {
            client.Method2(args);
        }
        catch(Exception) {
            // Cleanup
        }
    }

} 

class Client: IDisposable {
    public void Dispose()
    {

    }
}

我希望基类 CommunicationChannel 能够以某种方式拦截与客户端相关的所有调用,并在将异常传播到派生类 CommunicationChannel 之前处理异常。基类的泛型参数可以包含不同的方法(在我的例子中我们只有方法1)

理想情况下,我想要一个不必调用 CommunicationChannel.CallMethod("Method1", args) 的解决方案。

最佳答案

您可以将 client 设为私有(private)并强制子类在 FuncAction 中访问它。然后你可以在逻辑之前/之后添加你:

abstract class CommunicationChannel<Client> : IDisposable where Client : class, IDisposable
{
    private Client client;

        protected TResult WithClient<TResult>(Func<Client, TResult> f)
        {
            this.Open();
            try
            {
                return f(client);
            }
            catch (Exception)
            {
                //cleanup
            }

            return default(TResult);
        }

    protected void WithClient(Action<Client> act)
    {
        WithClient<object>(c => { act(c); return null; })
    }
}

然后你的子类可以做:

class Communicator : CommunicationChannel<Client> 
{
    bool Method1(args) 
    {
        return WithClient<bool>(c => { return c.Method1(args); });
    }
}

关于c# - 拦截泛型类中的方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23140825/

相关文章:

c# - 如何在两个 C# 应用程序之间创建状态加密连接?

java - Spring jdbcTemplate : generic code to run a select query with model name provided

java - 调用静态泛型方法

c# - Entity Framework CTP4 代码优先 : Mapping protected properties

Java 泛型类型删除 : when and what happens?

java - super 行为异常的通配符

Java Servlet - 需要使用 session 跟踪和泛型

c# - 不好的做法? c# 的 using 语句的非规范用法

c# - void 类型方法表达式主体成员允许非 void 类型的表达式*如果有其他方法*

c# - 使用正则表达式匹配一系列数字 1-9,没有重复