![](/img/trans.png)
[英]Kendo MVC C# is it possible to have generic fields in some kind of template to include easily in all grids?
[英]Is it possible to have some kind of inside storage for C# Windows App?
我创建了一个小应用程序,可以在单击按钮时生成一个随机数,此刻我将该数字保存在.txt文件中。
private void button1_Click(object sender, EventArgs e)
{
Random rnd = new Random();
int random = rnd.Next(1, 10000);
// saving to a file is not an option!
//File.AppendAllText(@"C:\Users\Public\no.txt", random + Environment.NewLine);
}
要解决的问题是,这个随机生成的数字必须唯一(范围从1到9999),因此每次生成该数字时,我都会检查该数字是否以前生成过。 但是要做到这一点,我必须记录每个生成的数字,以便能够检查,比较,如果存在,则生成一个新的数字,直到使用完所有数字为止。
所以问题是:是否有可能以某种方式在应用程序内保存记录,这样我就不必创建任何其他文件了?
关闭应用程序后,必须保存以前的号码才能创建唯一的新号码!
.NET程序集没有“内部存储”。 保存文件怎么了?
使用特殊文件夹而不是硬编码的字符串
考虑使用ProgramData或AppData
同样,如果您想轻松地管理运行时对象,则可以使用Serialization 。
您也可以使用注册表或数据库来保存数据。
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
randoms = string.IsNullOrEmpty(ConfigurationManager.AppSettings["randoms"]) ? new List<int>() : ConfigurationManager.AppSettings["randoms"].Split(',').Select(int.Parse).ToList();
Random rnd = new Random();
int random = rnd.Next(1, 10000);
if (!randoms.Contains(random))
{
randoms.Add(random);
config.AppSettings.Settings.Add("randoms", string.Join(",", randoms.Select(p => p.ToString()).ToList()));
config.Save(ConfigurationSaveMode.Minimal);
}
您可以在应用设置中定义密钥:
<configuration>
<appSettings>
<add key="randoms" value="" />
</appSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
</startup>
</configuration>
我不确定config.AppSettings.setting.Add的工作方式。 我认为它可以通过串联为前一个添加价值。
我认为简单的答案是调整功能在应用程序上下文中的工作方式。
我将更改逻辑如下:
调整数组大小的重要代码是:
// should be in an accessible class scope - public or maybe even static
int[] myList = new list[0]; //start at 0 or empty
//function ressize Array by 1, accessible class scope - public or even static
static public int[] incrementIntArrayBy1(int[] oldArray){
int[] newArray = new int[oldArray.Length + 1];
Array.Copy(oldArray, newArray, oldArray.Length);
return newArray;
}
//function on button
private void button1_Click(object sender, EventArgs e){
mylist = incrementIntArrayBy1(myList);
myList[myList.length-1] = new Random().Next(1, 1000);
}
我会稍微不同地生成随机数。
这样就不必检查所有数字以查看它们是否以前生成过,这在到达最后几个数字时可能会导致延迟。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.