问题描述
是否有一种方法可以将NameValueCollection(例如Request.Form或ConfigurationManager.AppSettings)作为动态对象访问?我希望能够做这样的事情:
Is there a way to access a NameValueCollection (like Request.Form or ConfigurationManager.AppSettings) as a dynamic object?I'd like to be able to do something like this:
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"]
(此问题基于将NameValueCollection转换为动态对象)
推荐答案
您可以编写一个包装NameValueCollection并继承自DynamicObject的适配器.然后,您可以创建实例化适配器的扩展方法.要结束它,您可以将包装器类隐式地转换为原始NameValueCollection,以便可以在可以使用原始集合的所有地方使用包装的集合:
You could write an adapter that wraps your NameValueCollection and that inherits from DynamicObject. You could then create an extension method that instantiates the adapter. To finish it off, you could make your wrapper class implicitly castable to you original NameValueCollection, so you could use the wrapped collection everywhere you would be able to use the original collection:
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);
}
}
}
这篇关于如何将NameValueCollection(例如Request.Form或ConfigurationManager.AppSettings)作为动态对象访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!