Mar*_*ela 7 c# dictionary list
A friend and I (both new in programming) were arguing if it was wise to include a Dictionary inside a Class that contains all instances of that class.
I say that is better that the dictionary is in the main instead in the class itself.
我没有充分的理由说出为什么,但是我从未见过有类记录已创建对象的记录。
您能给我每种方法的利弊吗?
提前致谢。
A:
class Table
{
public static Dictionary<int,Table> Tables = new Dictionary<int, Table>();
...
public table (int ID) // constructor
{
...
Tables.Add(ID,this);
}
}
Run Code Online (Sandbox Code Playgroud)
B:
class Program
{
public Dictionary<int,Table> Tables = new Dictionary<int, Table>();
static void Main(string[] args)
{
...
Table A = new Table (10);
Tables.Add(10,A);
}
}
Run Code Online (Sandbox Code Playgroud)
这主要取决于您的需求和您的架构/设计偏好。
在类中包含字典可以很好地封装所有与类相关的逻辑。这样,您可以向类用户隐藏(静态)字典,并由您的类在内部对其进行管理。
将字典放在课外可以使该机制以其他方式灵活使用。例如,您可以为您的类实例管理多个不同的字典(出于多种目的)。或者,如果您在特定的解决方案环境中不需要这样的词典,也可以将其丢掉。
恕我直言,没有严格的准则可以告诉您您应该或不应该做特定的事情。只要有创造力。只要最终结果清晰,可维护,可扩展等,天空就是极限。
好吧,A版本意味着你不能有两个 Table相同的ID.
using System.Collections.Concurrent;
...
public class Table {
//DONE: Do not expose fields but readonly properties
//DONE: Keep static (i.e. global) members (fields, properties, methods) being thread safe
private static ConcurrentDictionary<int, Table> s_Tables =
new ConcurrentDictionary<int, Table>();
public Table(int ID) {
s_Tables.Add(ID, this);
}
//DONE: All we expose is thead safe read-only version of the dictionary
public static IReadOnlyDictionary<int, Table> Tables = s_Tables;
}
Run Code Online (Sandbox Code Playgroud)
当B版本意味着您可以拥有多个版本时,Program每个版本都有自己的Table版本,这就是为什么版本ID不是全局唯一的:
public class Program {
//DONE: Do not expose fields but readonly properties
private Dictionary<int,Table> m_Tables = new Dictionary<int, Table>();
public Program() {
Table A = new Table (10);
m_Tables.Add(10,A);
...
}
//DONE: All we expose is read-only version of the dictionary
public IReadOnlyDictionary<int, Table> Tables = m_Tables;
}
...
//DONE: please, do not cram all the logic into `Main`,
// have a special classes business logic (Program) and entry point
public static class EntryPoint {
static void Main(string[] args) {
Program program = new Program();
...
}
}
Run Code Online (Sandbox Code Playgroud)
由于在您的原始代码中,您static void Main在Program类中它是有效的singleton,所以看来,版本A更可取:所有内容都Table在Table类内;您有时无法创建Table具有相同内容的第二个实例ID