.net 是否在数组中保存打开的泛型类型?
我面临.NET泛型的问题。我要做的是保存泛型类型数组(GraphicsItem):.net 是否在数组中保存打开的泛型类型?,.net,generics,.net,Generics,我面临.NET泛型的问题。我要做的是保存泛型类型数组(GraphicsItem): GraphicsItem公共类 { 私人信托基金项目; 公共空荷载(T项) { _项目=项目; } } 如何将此类打开的泛型类型保存到数组中?如果要存储异构GrpahicsItem,即GraphicsItem和GrpahicsItem,则需要从公共基类派生它们,或实现公共接口。另一个选项是将它们存储在列表中。您是否试图用非泛型方法创建GraphicsItem数组 您不能执行以下操作: static void f
GraphicsItem公共类
{
私人信托基金项目;
公共空荷载(T项)
{
_项目=项目;
}
}
如何将此类打开的泛型类型保存到数组中?如果要存储异构GrpahicsItem,即GraphicsItem
static void foo()
{
var _bar = List<GraphicsItem<T>>();
}
静态void foo()
{
var_bar=List();
}
然后再填清单
更可能的是,你正试图做这样的事情
static GraphicsItem<T>[] CreateArrays<T>()
{
GraphicsItem<T>[] _foo = new GraphicsItem<T>[1];
// This can't work, because you don't know if T == typeof(string)
// _foo[0] = (GraphicsItem<T>)new GraphicsItem<string>();
// You can only create an array of the scoped type parameter T
_foo[0] = new GraphicsItem<T>();
List<GraphicsItem<T>> _bar = new List<GraphicsItem<T>>();
// Again same reason as above
// _bar.Add(new GraphicsItem<string>());
// This works
_bar.Add(new GraphicsItem<T>());
return _bar.ToArray();
}
staticgraphicsitem[]CreateArrays()
{
GraphicsItem[]_foo=新GraphicsItem[1];
//这是行不通的,因为您不知道t==typeof(string)
//_foo[0]=(GraphicsItem)新建GraphicsItem();
//只能创建作用域类型参数T的数组
_foo[0]=新的GraphicsItem();
列表_bar=新列表();
//同样的原因如上所述
//_bar.Add(new GraphicsItem());
//这很有效
_添加(新的GraphicsItem());
返回_bar.ToArray();
}
请记住,您需要一个泛型类型引用来创建泛型类型的数组。这可以是在方法级别(在方法之后使用T)或在类级别(在类之后使用T)
如果希望该方法返回GraphicsItem和GraphicsItem的数组,则让GraphicsItem从非泛型基类GraphicsItem继承并返回该基类的数组。但是,您将失去所有类型安全性
希望这有帮助。实现一个非通用接口并使用它:
public class GraphicsItem<T> : IGraphicsItem
{
private T _item;
public void Load(T item)
{
_item = item;
}
public void SomethingWhichIsNotGeneric(int i)
{
// Code goes here...
}
}
public interface IGraphicsItem
{
void SomethingWhichIsNotGeneric(int i);
}
公共类GraphicsItem:IGraphicsItem
{
私人信托基金项目;
公共空荷载(T项)
{
_项目=项目;
}
公共无效的非通用的东西(int i)
{
//代码在这里。。。
}
}
公共接口IGM
{
使一些非一般的东西无效(inti);
}
然后将该界面用作列表中的项目:
var values = new List<IGraphicsItem>();
var值=新列表();
var values = new List<IGraphicsItem>();