Ury*_*shy 2 c# generics macros constraints
(语言是VS#的c#)
我有以下问题:有许多结构(按第3方提供)所有结构都使用相同的签名实现某些方法.我想用实现某个接口的包装类来包装这些结构,以便可以统一的方式处理这些类.例:
interface AnInterface
{
void DoSomething();
}
struct Struct1
{
public void DoSomething();
}
class Struct1Wrapper : AnInterface
{
private Struct1 m_struct;
public override void DoSomething() // AnInterface implementation
{
m_struct.DoSomething();
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,Struct1 DoSomething方法是具体的,而Struct1Wrapper通过接口实现它以便于处理.
Struct2等也是如此 - 除了Struct1替换的Struct1之外,StructXWrapper的代码是相同的
我尝试过使用泛型来避免代码重复:
class GenericStructWrapper<AStruct> : AnInterface
{
private AStruct m_struct;
public override void DoSomething() // AnInterface implementation
{
m_struct.DoSomething();
}
}
Run Code Online (Sandbox Code Playgroud)
但这不起作用,因为编译器没有关于AStruct DoSomething()方法的概念.
还有其他想法如何实现这一点而不重复Struct1Wrapper的代码?也许有一些宏观特征或一些反射的使用?
谢谢,
尤里·贾姆希.
您可以Action<AStruct>在接受该方法的类构造函数中使用.
然后,您可以创建像 new GenericStructWrapper<Struct1>(s => s.DoSomething())
| 归档时间: |
|
| 查看次数: |
316 次 |
| 最近记录: |