我们正在尝试在DAL之上构建某种层,以便使用泛型公开某些存储库方法的接口。
例如:
public interface A
{
void Do_A();
}
public interface B
{
void Do_B();
}
public void Main()
{
Exposer<A>.Do_A();
Exposer<B>.Do_B();
}
有可能吗?
答案 0 :(得分:2)
从技术上讲,这不是“单一班级”,因为Exposer<A>
是Type
到Exposer<B>
的不同之处。但是,最终,这与大多数IoC / DI容器没什么不同......如果这是,例如,StructureMap(纯粹是一个例子),你可能会考虑:
container.GetInstance<A>().Do_A();
container.GetInstance<B>().Do_B();
当然,您需要配置容器以了解具体A
和B
实现的来源!哪个适用于StructureMap is shown here,但有plenty to choose from。
如果您的意思是直接,那么:不。你不能拥有:
class Exposer<T> : T {...} // non-working code to implement the interface T
你可以但是有一些类:
class Exposer : A, B {...}
刚刚演员:
A a = Exposer;
a.Do_A();
B b = Exposer;
b.Do_B();
答案 1 :(得分:1)
类型Foo<T>
无法实现(或扩展)实际的T
,因为T
在编译时是未知的。你可以做的是将T
作为属性公开,并在其上调用方法。然而,正如Ondrej所写,这个问题可能有点不清楚。
答案 2 :(得分:1)
你在写作时是在描述IoC吗?
Exposer<A>.Do_A();
您的Exposer课让我想到了StructureMap API:
ObjectFactory.GetInstance<T>().Do_A();
如果您想删除关键字new
并以通用方式获取指定接口的实例,请查看此article或检查StructureMap
答案 3 :(得分:0)
要在使用给定类时选择所需的接口实现,不要使用泛型,只需将类强制转换为接口:
public interface A
{
void Do_A();
}
public interface B
{
void Do_B();
}
public class Exposer : A, B
{
public void Do_A() { ; }
public void Do_B() { ; }
}
public void Main()
{
// the casts are redundant here,
// because the interface implementation
// is implicit
((A)Exposer).Do_A();
((B)Exposer).Do_B();
}
如果您想排除 不给定接口成员实现的成员,请使用显式实现:
public class Exposer : A, B
{
void A.Do_A() { ; }
void B.Do_B() { ; }
}
public void Main()
{
// the casts are now required;
// otherwise, you'll get a compiler error
// telling you that the method is inaccessible
((A)Exposer).Do_A();
((B)Exposer).Do_B();
}