如何将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
派生并重写TryGetValue
和TrySetValue
来创建TrySetValue
ExpandoObject
的类。
上述就是C#学习教程:如何将ExpandoObject的字典设置为不区分大小写?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1273235.html