我有一些遗留代码,其中有一个名为foo的方法,它有700多个重载:
[DllImport("3rdparty.dll")]
protected static extern void foo(int len, ref structA obj);
[DllImport("3rdparty.dll")]
protected static extern void foo(int len, ref structB obj);
[DllImport("3rdparty.dll")]
protected static extern void foo(int len, ref structC obj);
//and 700 similar overloads for foo...
我希望使用泛型将这些重载方法通过单个方法公开:
public void callFoo<T>(int len)
where T : new() //ensure an empty constructor so it can be activated
{
T obj = Activator.CreateInstance<T>(); //foo expects obj to be empty, and fills it with data
foo(len, ref obj);
//...do stuff with obj...
}
不幸的是,这会返回错误:" foo(int, ref StructA)的最佳重载方法匹配有一些无效参数" 和 " 无法将'ref T'转换为'ref StructA'"。
有没有一种优雅的方法来实现这个?
classA
和classB
是否属于类继承体系?如果是,能否解释一下结构? - Oded