Does anyone have any suggestions as to how to go about designing a container class, in C#, that has upwards of thirty variables contained within it?
有没有人对如何在C#中设计容器类有任何建议,其中包含超过30个变量?
I have written it out as a set of variables, as there are a few different types, eg string or DateTime, however I am thinking that it would perhaps be better to house them all in a dictionary of objects with their property names as keys?
我把它写成一组变量,因为有一些不同的类型,例如字符串或DateTime,但是我认为将它们全部放在一个对象字典中并将它们的属性名称作为键可能会更好?
Cheers, Ed
1 个解决方案
#1
If all the fields are required, then they are required. Using a dictionary can only add overhead and incur extra memory costs. A dictionary approach may be useful in a few specific scenarios, such as property bag implementations, and sparse event handlers (since events are the most obvious sparse data).
如果需要所有字段,则需要它们。使用字典只会增加开销并产生额外的内存成本。字典方法在一些特定场景中可能是有用的,例如属性包实现和稀疏事件处理程序(因为事件是最明显的稀疏数据)。
If the fields are used sparsely (i.e. often not more than a few are in use), then perhaps push the related fields into a number of inner classes (per group of related fields) - i.e. instead of:
如果字段被稀疏地使用(即通常不超过几个使用),那么可能将相关字段推入多个内部类(每组相关字段) - 即代替:
class Foo {
string userName;
int userId;
string orderReference;
DateTime orderDate;
...
}
something like:
class Foo {
class UserInfo { // move this outside if it makes sense to re-use it
public int Name {get;set;}
public int Id {get;set;}
}
UserInfo user;
class OrderInfo { // move this outside if it makes sense to re-use it
public string Reference {get;set;}
public string Date {get;set;}
}
OrderInfo order;
}
Then when you have to store the user data, create a new UserInfo
; if you don't need the user data, leave user
null.
然后,当您必须存储用户数据时,创建一个新的UserInfo;如果您不需要用户数据,请将user保留为null。
#1
If all the fields are required, then they are required. Using a dictionary can only add overhead and incur extra memory costs. A dictionary approach may be useful in a few specific scenarios, such as property bag implementations, and sparse event handlers (since events are the most obvious sparse data).
如果需要所有字段,则需要它们。使用字典只会增加开销并产生额外的内存成本。字典方法在一些特定场景中可能是有用的,例如属性包实现和稀疏事件处理程序(因为事件是最明显的稀疏数据)。
If the fields are used sparsely (i.e. often not more than a few are in use), then perhaps push the related fields into a number of inner classes (per group of related fields) - i.e. instead of:
如果字段被稀疏地使用(即通常不超过几个使用),那么可能将相关字段推入多个内部类(每组相关字段) - 即代替:
class Foo {
string userName;
int userId;
string orderReference;
DateTime orderDate;
...
}
something like:
class Foo {
class UserInfo { // move this outside if it makes sense to re-use it
public int Name {get;set;}
public int Id {get;set;}
}
UserInfo user;
class OrderInfo { // move this outside if it makes sense to re-use it
public string Reference {get;set;}
public string Date {get;set;}
}
OrderInfo order;
}
Then when you have to store the user data, create a new UserInfo
; if you don't need the user data, leave user
null.
然后,当您必须存储用户数据时,创建一个新的UserInfo;如果您不需要用户数据,请将user保留为null。