gpt4 book ai didi

c# - 使用静态字典时,我在 ASP.NET 中收到错误 "Item has already been added."

转载 作者:太空宇宙 更新时间:2023-11-03 22:01:01 25 4
gpt4 key购买 nike

当我使用 f10 调试代码时,它可以正常工作,没有错误!但是在运行时我得到了这个错误:“已添加具有相同键的项目”

请帮忙

我的字典:

public static Dictionary<string, string> ImageFilePath
= new Dictionary<string, string>();

在同一个 Glob.cs 中使用我的函数:

public static Image ShowImageOnColumn(string Value,byte ImageHeigth,byte ImageWidth)
{

.
.
.

string FilePath = "",ImgId = "";


Image img_ = new Image();

Random rnd = new Random();

ImgId = rnd.Next(100000000).ToString();
img_.ImageUrl = "ShowImageInRuntime.aspx?FileName=" + ImgId;

ImageFilePath.Add(ImgId, FilePath);


img_.Height = Unit.Pixel(ImageHeigth);
img_.Width = Unit.Pixel(ImageWidth);

return img_;

}

最佳答案

您没有保护您的 ImageFilePath.Add 调用。如果 key 已经存在,您将得到一个异常提示。

您可以检查 key :

if (ImageFilePath.ContainsKey(ImgId))
{
ImageFilePath[ImgId] = FilePath;
}

或者你可以在索引上设置,如果它丢失则添加,如果存在则更新:

ImageFilePath[ImgId] = FilePath;

与调用 Add 相反。

但是请注意,当 IIS 回收工作进程时,静态成员容易丢失。因此,它们往往会被避免。还存在多线程问题,因为静态成员在整个进程中都是可见的。

如果您需要一个随机文件名,请尝试 DateTime.ToString("ddMMyyyyhhmmssfff")Guid.NewGuid(),而不是保留 随机活着。

Path 还具有 GetTempFileName 方法。

关于c# - 使用静态字典时,我在 ASP.NET 中收到错误 "Item has already been added.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10123895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com