C# WP7.1上的匿名类型和获取访问器?

C# WP7.1上的匿名类型和获取访问器?,c#,windows-phone-7,reflection,methodaccessexception,C#,Windows Phone 7,Reflection,Methodaccessexception,我正在尝试编写一个简单的对象到字典转换器,如下所示: public static class SimplePropertyDictionaryExtensionMethods { public static IDictionary<string,string> ToSimplePropertyDictionary(this object input) { if (input == null) return new Diction

我正在尝试编写一个简单的对象到字典转换器,如下所示:

public static class SimplePropertyDictionaryExtensionMethods
{
    public static IDictionary<string,string> ToSimplePropertyDictionary(this object input)
    {
        if (input == null)
            return new Dictionary<string, string>();

        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();
    }
}
然后它会失败,出现一个异常:

[System.MethodAccessException]: {"Attempt to access the method failed: .<>f__AnonymousType0`1.get_Foo()"}
[System.MethodAccessException]:{“尝试访问该方法失败:.f_uAnonymousType0`1.get_Foo()”}
这只是芒果上说“不”的安全模式吗?有什么办法吗?感觉这是一个公共Get访问器-所以感觉我应该能够调用它


斯图尔特删除BindingFlags.GetProperty

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

编辑:问题实际上可能与propertyInfo.getMethod()有关-请尝试使用以下选项之一(我只使用过第一个选项):


我猜您的
ToSimplePropertyDictionary
方法和实际用法在两个单独的程序集中。这是问题的根源,因为从匿名类生成的编译器生成的类是
internal
。这就是为什么会出现
MethodAccessException
异常。因此,您需要使用该工具使其工作。这包含有关内部类型和反射的更多信息。

mmm,回答得好。我从未想过这是BindingFlags。获取属性时会传递Public。我原以为,如果匿名类型是内部的,即使MSDN声明属性是公共的,也不会返回任何属性(如果父类不是公共的,这看起来很奇怪)。
[System.MethodAccessException]: {"Attempt to access the method failed: .<>f__AnonymousType0`1.get_Foo()"}
var value = propertyInfo.GetValue(input, null);
var value = propertyInfo.GetGetMethod().Invoke(input, null);