【问题标题】:Expose Methods in Properties as Single Class将属性中的方法公开为单个类
【发布时间】:2016-03-29 05:27:54
【问题描述】:

我需要将具有大量接口和客户端类的 WCF 服务合同分解为更小的类。所有较小的类都是相似的,但有不同的操作合同。我希望能够将所有新子类中的操作合同方法公开为单个类,以实现向后兼容性。理想情况下,它看起来像这样:

public class MainClient {

    public MainClient() {
        Sub1 = new Sub1Client();
        Sub2 = new Sub2Client();
    }

    public static Sub1Client Sub1;
    public static Sub2Client Sub2;
}

然后我希望能够从Sub1Sub2 调用方法,就好像这些方法是在MainClient 中定义的一样。所以我不会调用(new MainClient()).Sub1.Method1(),而是调用(new MainClient()).Method1(),其中Method1 仍然存在于Sub1Client 类中。

这可能吗?

【问题讨论】:

  • 你应该在MainClient中声明Method1,在MainClient.Method1里面是对Sub1.Method1的调用。
  • 啊,有道理。但从逻辑上讲,这是一场噩梦。我正在寻找一个 500K+ 行的神类,需要将其分解为至少 45 个子客户端,总体上具有约 2K 的操作合同,以使 xml 序列化相当快。从现在开始,一切都是正则表达式和祈祷。
  • 祝兄弟好运。 :)

标签: c# wcf design-patterns


【解决方案1】:

我不确定是否清楚地理解了您的问题,但请查看solution

public interface IFirst
{
    void Method1(string a);
}

public interface ISecond
{
    double Method2(int b, bool a);
}    

public interface IComplex : IFirst, ISecond
{
}

public class MyException : Exception
{
    public MyException(string message) : base(message)
    {
    }
}

public class Sub1Client : IFirst
{
    public void Method1(string a)
    {
        Console.WriteLine("IFirst.Method1");
        Console.WriteLine(a);
    }
}

public class Sub2Client : ISecond
{
    public double Method2(int b, bool a)
    {
        Console.WriteLine("ISecond.Method2");
        return a ? b : -b;
    }
}

public class MainClient : IComplex
{
    public MainClient()
    {
        Sub1 = new Sub1Client();
        Sub2 = new Sub2Client();
    }

    public static Sub1Client Sub1;
    public static Sub2Client Sub2;        

    private T FindAndInvoke<T>(string methodName, params object[] args)
    {
        foreach(var field in this.GetType().GetFields(BindingFlags.Public | BindingFlags.Static))
        {
            var method = field.FieldType.GetMethod(methodName);
            if(method != null)
                return (T)method.Invoke(field.GetValue(this), args);
        }
        throw new MyException("Method was not found!");
    }

    public void Method1(string a)
    {            
        FindAndInvoke<object>(MethodBase.GetCurrentMethod().Name, a);            
    }

    public double Method2(int b, bool a)
    {
        return FindAndInvoke<double>(MethodBase.GetCurrentMethod().Name, b, a);
    }
}    

public static void Main()
{
    var test = new MainClient();
    test.Method1("test");
    Console.WriteLine(test.Method2(2, true));
}

【讨论】:

    猜你喜欢
    • 2011-09-06
    • 1970-01-01
    • 1970-01-01
    • 2010-09-14
    • 2013-12-09
    • 1970-01-01
    • 1970-01-01
    • 2019-08-02
    相关资源
    最近更新 更多