有没有办法将NameValueCollection(如Request.Form或ConfigurationManager.AppSettings)作为动态对象进行访问? 我希望能够做到这样的事情:
var settings = ConfigurationManager.AppSettings.AsDynamic();
var name = settings.Name; // ConfigurationManger.AppSettings["Name"]
// but also
settings.Name = "Jones"; // modify the original collection
// and
var form = Request.Form.AsDynamic();
var email = form.Email; // Request.Form["Email"]
答案 0 :(得分:0)
您可以编写一个包装NameValueCollection并从DynamicObject继承的适配器。然后,您可以创建一个实例化适配器的扩展方法。要完成它,你可以使你的包装类隐式地转换为原始的NameValueCollection,所以你可以在任何地方使用包装的集合,你可以使用原始集合:
public static class Utility
{
public static dynamic AsDynamic(this NameValueCollection collection)
{
return (NameValueCollectionDynamicAdapter)collection;
}
private class NameValueCollectionDynamicAdapter : DynamicObject
{
private NameValueCollection collection;
public NameValueCollectionDynamicAdapter(NameValueCollection collection)
{
this.collection = collection ?? throw new NullReferenceException(nameof(collection));
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = collection[binder.Name];
return true;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
collection[binder.Name] = value?.ToString();
return true;
}
public static implicit operator NameValueCollection(NameValueCollectionDynamicAdapter target)
{
return target.collection;
}
public static explicit operator NameValueCollectionDynamicAdapter(NameValueCollection collection)
{
return new NameValueCollectionDynamicAdapter(collection);
}
}
}