您可以编写一个适配器来包装您的 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);
}
}
}