Generic list of generic objects

后端 未结 3 1338
醉梦人生
醉梦人生 2020-12-01 12:06

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         


        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-01 12:54

    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 class.

    Have Field implement the interface IField. This interface doesn't need any members.

    Then declare your list as being List.

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

提交回复
热议问题