[英]How to pass a Generic class as a Parameter to a non-generic class constructor
[英]How to pass a generic type through a non-generic class function
我有一个函数可以将通用数据从 API 复制到通用数组 ( apiData.copyTo()
)。 我通过执行以下操作解决了这个问题:
public class Foo<T> {
T[] data;
public void SetData(Action<T[]> action) {
action.Invoke(data);
}
}
// ushort as example:
Foo<ushort> someFoo;
someFoo.SetData(buffer => apiData.copyTo(buffer));
但是,在对数据布局进行一些更改后,我想为通用数据创建一个私有类并使 Foo 类成为非通用类,这会导致我面临以下问题:
public class Foo {
private class Bar<T> {
T[] data;
public void SetData(Action<T[]> action) {
action.Invoke(data);
}
}
private Bar<ushort> bar; // Example generic, could be everything
// The problem lies here:
// T is not known to Foo, how to fix this?
public void SetData(Action<T[]> action) {
bar.SetData(action);
// Some other stuff...
}
}
如您所见,问题在于Foo
类不知道泛型类型T
我怎样才能将Action
传递给Foo
的私有类Bar<T>
?
请注意,这是使我的问题清晰的最小示例。
我认为这将满足您的要求:
public class Foo
{
public interface IBar
{
void SetData<T>(Action<T[]> action);
Type GetBarType();
}
private class Bar<T>: IBar
{
//I changed this to a list since an empty array probably won't do you much good.
List<T> data = new List<T>();
public Type GetBarType()
{
return typeof(T);
}
public void SetData<TAction>(Action<TAction[]> action)
{
if(typeof(T) == typeof(TAction))
action.Invoke(data as TAction[]);
}
}
private IBar bar;
public void SetData<T>(Action<T[]> action)
{
if(bar?.GetBarType() == typeof(T))
bar.SetData(action);
else
{
bar = new Bar<T>();
bar.SetData(action);
}
// Some other stuff...
}
}
public class DoStuff
{
public DoStuff()
{
var foo = new Foo();
foo.SetData<int>((data) => { /*do somthing wth this container*/ });
foo.SetData<byte>((data) => { /*do somthing wth this container*/ });
foo.SetData<ushort>((data) => { /*do somthing wth this container*/ });
foo.SetData<ulong>((data) => { /*do somthing wth this container*/ });
foo.SetData<string>((data) => { /*do somthing wth this container*/ });
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.