Find the name of the class that eventually does work in a string of method calls

时间:2015-10-30 22:52:13

标签: c# .net nhibernate

I have a problem I need to solve and it revolves around the idea of code like the following.

public class x {
    private y yInstance;
    public bool doSomething(){
        return y.doSomething();
    }
}

public class y {
    private z zInstance;
    public bool doSomething(){
        return z.doSomething();
    }
}

public class z {
    public bool doSomething(){
        return true;
    }
}

I would like to, having an instance of x, beable to find out the class which actually does the work, in this case it is "z". However, in my case there can be any number of layers and more than one path could lead to the final class. Please let me know if I need to clarify anything.

Note: I need to do this without actually calling the method

Is this possible?

EDIT: This is very poor pseudo-code to demonstrate my use-case a little better as suggested. Note that in my repository I am using Nhibernate criteria.

public IEnumberable<T> GetByCriteria(DetachedCriteria criterion){
    if(criterion.Type.getFilterBase() == a)
        criterion.AppendFilter_a();
    if(criterion.Type.getFilterBase() == b)
        criterion.AppendFilter_b();
    if(criterion.Type.getFilterBase() == c)
        criterion.AppendFilter_c();
    return criterion.execute();
}

This is the idea. Note that in my case there are only 4 possible bases.

1 个答案:

答案 0 :(得分:1)

This is actually called the decorator pattern.

You could implement kind of a recursive function:

public class x {
    private y yInstance;
    public bool doSomething(){
        return y.doSomething();
    }
    public Type getWorkerClassType(){
        return yInstance.getWorkerClassType();
    }
}

public class y {
    private z zInstance;
    public bool doSomething(){
        return z.doSomething();
    }
    public Type getWorkerClassType(){
        return zInstance.GetType();
    }
}

public class z {
    public bool doSomething(){
        return true;
    }
}
相关问题