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

时间:2011-10-13 20:26:30

标签: c# .net visual-studio-2010 dynamic expandoobject

给出以下代码

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

一样有效

似乎没有明显的方法,也许是黑客攻击?

5 个答案:

答案 0 :(得分:8)

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

它类似于Darin's MassiveExpando答案,因为它为您提供字典支持,但通过将其作为字段公开,它可以节省为IDictionary实现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);
    }
}

答案 1 :(得分:5)

您可以签出Massive's实施MassiveExpando这是一个不区分大小写的动态对象。

答案 2 :(得分:1)

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

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.

答案 3 :(得分:0)

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

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

答案 4 :(得分:0)

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

相关问题