我需要将具有大量接口和clientbase类的WCF服务契约分解为更小的类。所有较小的类都相似但具有不同的操作合同。我希望能够将所有新子类中的操作契约方法公开为单个类,以实现向后兼容。理想情况下,它看起来像这样:
public class MainClient {
public MainClient() {
Sub1 = new Sub1Client();
Sub2 = new Sub2Client();
}
public static Sub1Client Sub1;
public static Sub2Client Sub2;
}
然后我希望能够从Sub1
和Sub2
调用方法,就好像这些方法是在MainClient
中定义的那样。因此,我不会致电(new MainClient()).Sub1.Method1()
而是致电(new MainClient()).Method1()
,其中Method1
类仍然存在Sub1Client
。
这可能吗?
答案 0 :(得分: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));
}