将 http post 变量转换为匿名类型

Convert http post variables to an anonymous type

我有一个 ashx 页面设置来处理来自服务的传入 http 帖子。

而且我想知道是否有比手动填充匿名类型更好的方法。例如。

public class myclass
{
    [key]
    public int ID { get; set; }
    public int field1 { get; set; }
    public int field2 { get; set; }
}

然后在我的 ashx 页面上

myclass mc = new myclass();

mc.field1 = context.Request.Form[field1];
mc.field2 = context.Request.Form[field2];

难道没有一种方法可以将其转换或转换为我的类型吗?

myclass mc = new myclass();
mc = context.Request.Form;

如果 "better" 你的意思是性能不是你最关心的问题的单一衬里,确保你可以通过基于请求上下文中的键过滤掉潜在属性来在 Reflection 中做到这一点。

mc.GetType().GetProperties()
    .Where (x => context.Request.Form.AllKeys.Contains(x.Name)).ToList()
    .ForEach(x => 
        x.SetValue(mc, Convert.ChangeType(context.Request.Form[x.Name], x.PropertyType)));

也就是说,这对空检查/类型检查有弹性吗?没有。性能好吗?一点也不。它可读吗?光是写它,我就把自己搞糊涂了三遍。因此,虽然可以做这样的事情,但这并不意味着它更好。有时手动拉出每个 属性 是最好的方法。

此外,您可以使用此扩展方法。 (我没有实施 null 检查或类型检查)

public static class ObjectExtensions
    {
        public static void SetValue(this object self, string name, object value)
        {
            PropertyInfo propertyInfo = self.GetType().GetProperty(name);
            propertyInfo.SetValue(self, Convert.ChangeType(value, propertyInfo.PropertyType), null);
        }
        public static void SetValues(this object self, NameValueCollection nameValues) {

            foreach (var item in nameValues.AllKeys)
            {
                SetValue(self, item, nameValues[item]);
            }
        }
    }

这样:

  myclass mc = new myclass();
  mc.SetValues(Request.Form);