通用对象的通用列表 [英] Generic list of generic objects
问题描述
class Field< T>
{
public string Name {get;组; }
public Type Type
{
get
{
return typeof(T);
}
}
public int Length {get;组; }
public T Value {get;组; }
}
我使用泛型,因为我想强制代码的用户只能分配某个类型的值。
现在问题是当我想创建一个字段列表。
如果我创建列表像 List< Field< object>>
然后我们可以将任何值赋给列表上的给定字段,当我们查询Type时,我们得到'object'。
事情是 - 在该列表中,我可能需要几个字段持有字符串,很少持有整数,日期,甚至自定义对象,反过来将有一个字段列表...
泛型是一个很好的这样的解决方案?如果是的话,我将如何去实施它?如果不是,什么是更好的方法?
---编辑---
只需添加一些背景:
1.我可能需要一个列表
List< Field< object>>字段,并且每个字段将保存不同的数据类型,如下所示: lst = new List< Field< object>>();
lst.Add(新字段< string>());
lst.Add(new Field< int>());
lst.Add(新字段< SomeObjectFromMyApp>());
2。稍后,我将不得不查询这些对象,并在一个循环中自动查询它们的属性,如下所示:
foreach(Field<对象> fld in lst)
{
类型t = fld.Type;
//做一些其他的东西
}
Field< T>之间添加一个抽象。 / code> class。
使字段< T>
实现接口
然后声明你的列表为 List< IField>
通过这种方式,您可以限制列表仅包含字段,但每个字段都可以是不同的类型。
以后再读取值,只需做
$ $ $ $ $ $ $ foreach $ list $
$ b var type = field.Type;
....
}
Let's say I have an object that represents a field of data, that object needs the following properties: Name, Type, Value, Length. Here is the object:
class Field<T>
{
public string Name { get; set; }
public Type Type
{
get
{
return typeof(T);
}
}
public int Length { get; set; }
public T Value { get; set; }
}
I have used generics, because I want to force the user of the code to only be able to assign a Value of certain Type.
Now the problem is when I want to create a list of fields.
If I create the list like List<Field<object>>
then we can assign any Value to a given Field on the list, and when we query for Type, we get 'object'.
The thing is - on that list I might want few fields holding strings, few holding ints, dates, and even custom objects that in turn will have a list of Fields...
Is the Generics a good solution for something like that? If yes, how would I go about implementing it? If not, what is a better way?
---EDIT---
Just to add some more background:
1. I might want a list of fields, and each field will hold different data type, like so :
List<Field<object>> lst = new List<Field<object>>();
lst.Add(new Field<string>());
lst.Add(new Field<int>());
lst.Add(new Field<SomeObjectFromMyApp>());
2. Later on I will have to query these objects, and their attributes automaticaly in a loop, something like that:
foreach(Field<object> fld in lst)
{
Type t = fld.Type;
//do some other stuff
}
Yes, generics is a good choice. The key to achieving type-safety (and being identify the type with the Type
property is to add an abstraction between the list and Field<T>
class.
Have Field<T>
implement the interface IField
. This interface doesn't need any members.
Then declare your list as being List<IField>
.
That way you constrain the list to only contain fields, but each field can be of a different type.
To then read the values later, just do
foreach(var field in list)
{
var type = field.Type;
....
}
这篇关于通用对象的通用列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!