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

本文关键字:不区 大小写 设置 字典 expandooobject | 更新日期: 2023-09-27 18:11:16

给定下面的代码

dynamic e = new ExpandoObject();
var d = e as IDictionary<string, object>;
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一样有效

似乎没有一个明显的方法,也许是一个hack ?

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

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

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

public class Flexpando : DynamicObject {
    public Dictionary<string, object> Dictionary
        = new Dictionary<string, object>(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);
    }
}

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

更多的是作为一种好奇心而不是作为一种解决方案:

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.

另一个解决方案是通过从System.Dynamic.DynamicObject派生并覆盖TryGetValueTrySetValue来创建一个类似ExpandoObject的类。

public static class IDictionaryExtensionMethods
{
  public static void AddCaseInsensitive(this IDictionary dictionary, string key, object value)
  {
    dictionary.Add(key.ToUpper(), value);
  }
  public static object Get(this IDictionary dictionary, string key)
  {
    return dictionary[key.ToUpper()];
  }
}