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

Stu*_*art 10 c# reflection windows-phone-7 methodaccessexception

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

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

var test = (new { Foo="12", Bar=15 }).ToSimplePropertyDictionary();
Run Code Online (Sandbox Code Playgroud)

然后失败并发生异常:

[System.MethodAccessException]: {"Attempt to access the method failed: .<>f__AnonymousType0`1.get_Foo()"}
Run Code Online (Sandbox Code Playgroud)

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

斯图尔特

nem*_*esv 8

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