WP7.1上的匿名类型和Get访问器?

我正在尝试将一个简单的对象写入Dictionary转换器,如下所示:

public static class SimplePropertyDictionaryExtensionMethods { public static IDictionary ToSimplePropertyDictionary(this object input) { if (input == null) return new Dictionary(); var propertyInfos = from property in input.GetType() .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.GetProperty) where property.CanRead select property; return propertyInfos.ToDictionary(x => x.Name, x => input.GetPropertyValueAsString(x)); } public static string GetPropertyValueAsString(this object input, PropertyInfo propertyInfo) { var value = propertyInfo.GetGetMethod().Invoke(input, new object[] {}); if (value == null) return string.Empty ; return value.ToString(); } } 

但是,当我尝试将其称为:

 var test = (new { Foo="12", Bar=15 }).ToSimplePropertyDictionary(); 

然后失败并发生exception:

 [System.MethodAccessException]: {"Attempt to access the method failed: .f__AnonymousType0`1.get_Foo()"} 

这只是Mango的安全模型说“不”吗? 它有什么办法吗? 感觉这是一个公共的Get访问器 – 所以感觉我应该能够调用它?

斯图尔特

我猜你的ToSimplePropertyDictionary方法和实际用法是在两个单独的程序集中。 这是您的问题的根源,因为从匿名类生成的编译器生成的类是internal 。 这就是您获得MethodAccessExceptionexception的原因。 因此,您需要使用InternalsVisibleToAttribute来使其工作。 这个SO问题包含有关内部类型和reflection的更多信息。

删除BindingFlags.GetProperty

这用于在使用InvokeMember时获取属性值,它不指定您希望返回只读属性。

编辑:问题可能实际上是propertyInfo.GetGetMethod() – 尝试使用以下之一(我只使用过第一个):

 var value = propertyInfo.GetValue(input, null); var value = propertyInfo.GetGetMethod().Invoke(input, null);