If one has a worksheet class which contains a collection of cells, in C# 4 how would one construct the cells in such a way that they can contain differing wrapped types (int, bool, string, etc.) and yet still co-exist in the same collection?
If it were something like the following,
public class Cell<T>
{
T CellValue {get;set;}
}
then the collection would need to be specific to T.
I wanted to avoid boxing, so I'm trying to get around having CellValue 开发者_高级运维be an object as it can contain value types.
The other option I had considered was to have specific cell types for each type I wish to support inherit from an abstract base that defines methods like GetAsString(), GetAsInt(), etc. which would return null or the value if the type matches or a conversion is possible and just use nullable value types. Then I'd have to write SetFromString(string val), etc. This would work as the consumer will always know what type it needs, but it seems a little clunky.
Is there another option I'm missing?
Boxing is the least of your worries. A spreadsheet is a huge project and even in the best design performance is much more likely to be limited by recalculation overhead like formulas and references than cell retrieval. But it is good to be thinking about it.
If you really want to do this thing then you probably don't want to go with the generic approach because that would benefit you with compile time safety but it would just create a big switch statement at run-time when you are trying to do things dynamically. Instead you can just use a traditional object-oriented approach of a base-class Cell
and derived NumberCell
and StringCell
classes and sure, go ahead and have a CellValue
of type object
. You might also like to add a CellType
property. You have a lot of options.
In addition the traditional object-oriented approach allows to add different kind of cell behavior in addition to cell value types such as formula cells, etc. On the other hand, some people might just create a single Cell
class and cram everything into it.
精彩评论