C# 别名接口
我有一个实现基本接口的接口。我们用于常见数据库任务的模式。然后我有一个工厂类,它返回接口的具体实现 虽然这很好,但我目前必须为每个接口创建一个具体的类,即使该接口目前除了第一个之外没有其他方法C# 别名接口,c#,interface,C#,Interface,我有一个实现基本接口的接口。我们用于常见数据库任务的模式。然后我有一个工厂类,它返回接口的具体实现 虽然这很好,但我目前必须为每个接口创建一个具体的类,即使该接口目前除了第一个之外没有其他方法 public static class Factory { public static T Resolve<T>() where T : class { if (typeof(T) == typeof(ICustomerRepo)) r
public static class Factory
{
public static T Resolve<T>() where T : class
{
if (typeof(T) == typeof(ICustomerRepo))
return (new CustomerRepo()as T);
else if (typeof(T) == typeof(ISalesOrderRepo))
return (new SalesOrderRepo() as T);
else
return null;
}
}
public interface IBaseRepo<C> where C: class, new()
{
C GetDataById(int Id);
}
public class BaseRepo<C> : IBaseRepo<C>
{
public C GetDataById(int Id)
{
// ... Do Work
return default(C);
}
}
public interface ICustomerRepo : IBaseRepo<Customer>
{
}
public class CustomerRepo: BaseRepo<Customer>, ICustomerRepo
{
}
public interface ISalesOrderRepo : IBaseRepo<SalesOrder>
{
List<SalesOrder> GetAllOrders();
}
public class SalesOrderRepo : BaseRepo<SalesOrder>, ISalesOrderRepo
{
public List<SalesOrder> GetAllOrders()
{
throw new NotImplementedException();
}
}
我知道严格来说这是不可能的,因为子接口(icCustomerRepo
)可能有编译器不知道的其他方法
我也可以让调用代码询问IBaseRepo
而不是iccustomerepo
,这将得到相同的结果,但我更希望调用代码继续引用iccustomerepo
是否有任何模式允许我创建名为ICCustomerRepo的IBaseRepo的别名,这意味着我可以稍后创建一个具体的实现,而无需更改调用代码?这在简单的方式中是不可能的-您希望返回实现ICCustomerRepo的类的实例,但BaseRepo没有实现它 唯一的解决方案是动态地(使用Reflection.Emit)发出ICCustomerRepo接口的实现,但它需要比添加CustomerRepo更多的工作
public static class Factory
{
public static T Resolve<T>() where T : class
{
if (typeof(T) == typeof(ICustomerRepo))
return (new BaseRepo<Customer>() as T);
else if (typeof(T) == typeof(ISalesOrderRepo))
return (new SalesOrderRepo() as T);
else
return null;
}
}