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

时间:2011-11-25 19:19:18

标签: c# windows-phone-7 reflection 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();
    }
}

然而,当我试着这样称呼时:

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

然后失败,但有例外:

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

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

斯图尔特

2 个答案:

答案 0 :(得分:8)

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

答案 1 :(得分:1)

删除BindingFlags.GetProperty

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

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

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