- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这个问题是关于 .Net Framework 4.5 MVC Web 应用程序的。
我有一段我们继承并使用了多年的代码块,它一般将 DataTable 转换为 List
原始代码
private static Dictionary<Type, IList<PropertyInfo>> typeDictionary = new Dictionary<Type, IList<PropertyInfo>>();
public static IList<PropertyInfo> GetPropertiesForType<T>()
{
//variables
var type = typeof(T);
//get types
if (!typeDictionary.ContainsKey(typeof(T)))
{
typeDictionary.Add(type, type.GetProperties().ToList());
}
//return
return typeDictionary[type];
}
没有什么令人兴奋的事情发生,只是确保 typeDictionary 不包含键(类型)并将其添加到字典中(key=type,value=properties),以便我们稍后可以访问它们。
我们通常将此代码用于任何类型的“模型”对象,但对于这个特定示例,这是在 2 个不同场合给我带来麻烦的代码。
模型对象
public class GetApprovalsByUserId
{
// constructor
public GetApprovalsByUserId()
{
TicketId = 0;
ModuleName = string.Empty;
ModuleIcon = string.Empty;
ApprovalType = string.Empty;
VIN = string.Empty;
StockNumber = string.Empty;
Year = 0;
Make = string.Empty;
Model = string.Empty;
Services = string.Empty;
RequestedDate = DateTime.MinValue;
}
// public properties
public int TicketId { get; set; }
public string ModuleName { get; set; }
public string ModuleIcon { get; set; }
public string ApprovalType { get; set; }
public string VIN { get; set; }
public string StockNumber { get; set; }
public int Year { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public string Services { get; set; }
public DateTime RequestedDate { get; set; }
}
同样,在那个特定的模型类中没有任何真正重要的事情发生,并且与我们在任何其他类中使用的没有任何不同。
就像我说的,我们在几个项目中普遍使用这段代码,并且从来没有遇到过问题,但在过去一天的 2 个不同场合,我们让它抛出以下异常:
已添加具有相同 key 的项目。
at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
at Utilities.Extensions.GetPropertiesForType[T]()
at Utilities.Extensions.ToObject[T](DataRow row)
at Utilities.Extensions.ToList[T](DataTable table)
如果有帮助,您可以在此处查看扩展方法所在的完整 Extensions.cs 类(静态):
https://pavey.azurewebsites.net/resources/Extensions.txt
我的问题是:
鉴于代码已经在执行 !typeDictionary.ContainsKey(typeof(T)) 检查,它怎么可能通过该测试,但在typeDictionary.Add(type, type.GetProperties().ToList()); 调用?
为什么会这么零星?它似乎在 99% 的时间都有效,使用相同的代码、相同的类(GetApprovalsByUserId,如上所示),并且在任何其他项目或任何其他模型类中从未失败过。
我们无法能够在任何环境中使用完全相同的代码、模型、数据或完全相同的设置来重现此问题,因此不确定如何再保护此代码比现在更好。
我的一个想法是将代码更改为:
提议的代码更改
private static Dictionary<Type, IList<PropertyInfo>> typeDictionary = new Dictionary<Type, IList<PropertyInfo>>();
public static IList<PropertyInfo> GetPropertiesForType<T>()
{
//variables
var type = typeof(T);
IList<PropertyInfo> properties = null;
//get types
try
{
if (!typeDictionary.ContainsKey(type))
{
typeDictionary.Add(type, type.GetProperties().ToList());
}
}
catch
{
}
// try get value
typeDictionary.TryGetValue(type, out properties);
// return
return properties;
}
但是由于我一开始就无法重现错误,所以我也不完全确定这是否是防弹的。我的想法是,它只是 ContainsKey 的一些奇怪之处,特别是使用 typeof(T) 作为“键”时,它允许它在奇怪的情况下通过测试,而实际上不应该通过测试,但是 Add 失败,因为它知道 key 已经存在。因此,如果我尝试/捕获它,如果 ContainsKey 错误地告诉我它不存在,而实际上它不存在,Add 仍然会失败,但我会捕获它并继续,然后我可以 TryParse 获取值出来了,一切都会好起来的。
感谢任何想法、想法,或者特别是如何使用上面显示的原始代码重现问题,并提出改进建议以保护它。
最佳答案
您遇到的问题是并发访问。在检查和插入字典之间,另一个线程进来并添加了类型,导致第二次插入失败。
要解决此问题,您有两种选择:使用锁(如其他答案中所述)或使用 ConcurrentCollection:
using System.Collections.Concurrent;
private static ConcurrentDictionary<Type, IList<PropertyInfo>> typeDictionary = new ConcurrentDictionary<Type, IList<PropertyInfo>>();
public static IList<PropertyInfo> GetPropertiesForType<T>()
{
//variables
var type = typeof(T);
typeDictionary.TryAdd(type, type.GetProperties().ToList());
//return
return typeDictionary[type];
}
如果值不存在则添加该值并返回true,否则什么都不做并返回false
关于C# System.Collections.Generic.Dictionary`2.Insert - 已添加具有相同键的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40004119/
generic parameters of trait function 的简单示例: trait Ext: Sized { fn then(self, f: fn(Self) -> R) -
在下面的代码中,为什么 Groovy 似乎忽略了方法 barMany 中提供的闭包参数的泛型类型声明: import groovy.transform.CompileStatic @CompileSt
据我所知,Prolog 没有任何内置机制用于generic programming。 .可以使用统一来模拟泛型,但这需要在运行时进行类型检查: :- initialization(main). :-
在我的应用程序中,我有一个 Board。董事会由细胞组成。每个单元格都有一个 int 值。有几种类型的 Board 可以扩展 Board。每种类型的板将以不同方式表示单元格。例如,一个人会使用 Lis
我想将存储的属性添加到 UIView 子类中,例如UIView、UIImageView、UIPickerView等, 我只需要从子类创建 UIView 的实例子类仅类型不同,所有属性和方法都相同。 T
这个问题在这里已经有了答案: Any type and implementing generic list in go programming language (2 个答案) 关闭 6 个月前。
我有以下代码as seen in ideone.com : import java.util.*; class Test{ interface Visitor{ public
在 Swift 中,我们可以对序列等通用项编写扩展: extension Sequence where Iterator.Element : ObservableType { } 这将保证扩展仅适用于
我知道这听起来很困惑,但这是我能解释的最好的了。 (您可以建议一个更好的标题)。我有 3 节课:- A public class A > { ... } B public class B {
我目前在大学攻读 CS,我刚刚开始学习数据结构和算法类(class)。我的教授非常喜欢(实际上是强制我们)使用 Ada。为了取得成功,我开始查找一些东西并找到了这段代码,它描述了如何编写通用堆栈: g
我正在玩 Scala By Example 开头的 QuickSort 示例并尝试将其调整为通用类型 A ,而不仅仅是 Int s。 到目前为止我的工作是 def sort[A new Y(i, -
谁能解释为什么下面的第二个例子不能编译? “测试 2”给出“错误 FS0670:此代码不够通用。类型变量 ^a 无法泛化,因为它会超出其范围。”。我无法理解此错误消息。 // Test 1 type
如何将泛型存储在非泛型对象持有的泛型TList中? type TXmlBuilder = class type TXmlAttribute= class Name: Str
我正在尝试通过遵循 wiki article 创建如何使用 GHC.Generics 的最小工作示例.这是我所拥有的: {-# LANGUAGE DefaultSignatures, DeriveGe
我正在尝试将 get 函数添加到 wiki 中描述的通用序列化中。 。有些部分看起来很简单,但有一些地方我非常不确定要写什么,毫不奇怪,我遇到了编译错误。我已经查看了原始论文以及 cereal 中的实
为什么这段代码有效? $v):void { print_r($v); } test(Vector {1, array("I'm an array"), 3}); 它不应该抛出错误吗?什么是应
有没有办法让 Rust Generic 只接受原始类型?我想稍后迭代值中的位,并且我知道这只有在原始类型中才有可能。 struct MyStruct { my_property: T // m
假设我有一个简单的类 public class MyObject { } 以及处理MyObject子类的handler接口(interface) public interface MyObjectHa
出于某种原因,我正在努力通过使用通用基类来实现通用接口(interface)的属性,如下所示: public interface IParent where TChild : IChild {
我收到以下错误。 google了一天多,还是找不到具体的解决方法,求大神指点,谢谢 ERROR: Cannot implicitly convert type System.Collections.G
我是一名优秀的程序员,十分优秀!