0

有没有办法将 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"]

(此问题基于将 NameValueCollection 转换为动态对象

4

1 回答 1

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);
            }
        }
    }
于 2017-05-08T22:10:19.437 回答