我的应用程序要求我打印N次值X.
所以,我可以这样做:
Dictionary<int, string> toPrint = new Dictionary<int, string>();
toPrint.Add(2, "Hello World");
Run Code Online (Sandbox Code Playgroud)
...以后我可以使用此信息打印2页,文本值均为"Hello World".
我遇到的问题是,词典真的希望第一个值是Key:
Dictionary<TKey, TValue>
Run Code Online (Sandbox Code Playgroud)
因此,如果我想添加2个文本值为"Hello World"的页面,然后另外2个带有"Goodbye World"的页面,我有一个问题 - 它们都有一个TKey值为2,这会导致运行时错误("一项"已添加相同的键").
导致错误的逻辑:
Dictionary<int, string> toPrint = new Dictionary<int, string>();
toPrint.Add(2, "Hello World");
toPrint.Add(2, "Goodbye World");
Run Code Online (Sandbox Code Playgroud)
我仍然需要这个概念/逻辑才能工作,但由于Key,我显然不能使用Dictionary类型.
有没有人有任何解决方案的想法?
Chr*_*ler 15
我认为Tuple对于这项工作来说是完美的.
List<Tuple<int, string>> toPrint = new List<Tuple<int, string>>();
toPrint.Add(new Tuple<int, string>(2, "Hello World");
toPrint.Add(new Tuple<int, string>(2, "Goodbye World");
Run Code Online (Sandbox Code Playgroud)
并且......你可以轻松地将它包装成一个自包含的类.
public class PrintJobs
{
// ctor logic here
private readonly List<Tuple<int, string>> _printJobs = new List<Tuple<int, string>>();
public void AddJob(string value, int count = 1) // default to 1 copy
{
this._printJobs.Add(new Tuple<int, string>(count, value));
}
public void PrintAllJobs()
{
foreach(var j in this._printJobs)
{
// print job
}
}
}
Run Code Online (Sandbox Code Playgroud)
}
Ste*_*eve 13
在这种情况下,使用List <T>就足够了
class PrintJob
{
public int printRepeat {get; set;}
public string printText {get; set;}
// If required, you could add more fields
}
List<PrintJob> printJobs = new List<PrintJob>()
{
new PrintJob{printRepeat = 2, printText = "Hello World"},
new PrintJob{printRepeat = 2, printText = "Goodbye World"}
}
foreach(PrintJob p in printJobs)
// do the work
Run Code Online (Sandbox Code Playgroud)