Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
517 views
in Technique[技术] by (71.8m points)

c# - Generic list of generic objects

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
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
    ....
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...