如何将ExpandoObject的字典设置为不区分大小写?

给出下面的代码

dynamic e = new ExpandoObject(); var d = e as IDictionary; for (int i = 0; i < rdr.FieldCount; i++) d.Add(rdr.GetName(i), DBNull.Value.Equals(rdr[i]) ? null : rdr[i]); 

有没有办法让它不区分大小写,所以给定字段名称employee_name

e.Employee_name与e.employee_name一样有效

似乎没有一个明显的方式,也许是一个黑客?

您可以检查Massive的 MassiveExpando 的实现,它是不区分大小写的动态对象。

我一直在使用这个“Flexpando”类(用于灵活的expando),它不区分大小写。

它类似于Darin的MassiveExpando答案,因为它为您提供字典支持,但通过将其作为字段公开,它节省了必须为IDictionary实现15个左右的成员。

 public class Flexpando : DynamicObject { public Dictionary Dictionary = new Dictionary(StringComparer.OrdinalIgnoreCase); public override bool TrySetMember(SetMemberBinder binder, object value) { Dictionary[binder.Name] = value; return true; } public override bool TryGetMember(GetMemberBinder binder, out object result) { return Dictionary.TryGetValue(binder.Name, out result); } } 

更多的是好奇心而不是解决方案:

 dynamic e = new ExpandoObject(); var value = 1; var key = "Key"; var resul1 = RuntimeOps.ExpandoTrySetValue( e, null, -1, value, key, true); // The last parameter is ignoreCase object value2; var result2 = RuntimeOps.ExpandoTryGetValue( e, null, -1, key.ToLowerInvariant(), true, out value2); // The last parameter is ignoreCase 

RuntimeOps.ExpandoTryGetValue/ExpandoTrySetValue使用可控制区分大小写的ExpandoObject内部方法。 null, -1,参数取自ExpandoObject内部使用的值( RuntimeOps直接调用ExpandoObject的内部方法)

请记住,这些方法是This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.

public static class IDictionaryExtensionMethods
{
public static void AddCaseInsensitive(此IDictionary字典,字符串键,对象值)
{
dictionary.Add(key.ToUpper(),value);
}

public static object Get(这个IDictionary字典,字符串键)
{
返回字典[key.ToUpper()];
}
}

另一种解决方案是通过从System.Dynamic.DynamicObject派生并重写TryGetValueTrySetValue来创建TrySetValue ExpandoObject的类。