匿名类型和获取访问的WP7.1? [英] Anonymous types and Get accessors on WP7.1?

查看:94
本文介绍了匿名类型和获取访问的WP7.1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个简单的对象字典器象下面这样:

I'm trying to write a simple object to Dictionary converter like below:

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();
    }
}



然而,当我尝试调用此类似:

However, when I try to call this like:

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



然后失败,出现异常:

Then it fails with an exception:

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

这只是芒果的安全模式说不?有没有办法解决它的任何方式吗?感觉就像这是一个公共Get访问? - 所以感觉好像我应该能够调用它。

Is this just the security model on Mango saying "No"? Is there any way around it? It feels like this is a public Get accessor - so it feels like I should be able to invoke it?

司徒

推荐答案

我想,你的 ToSimplePropertyDictionary 方法和实际使用情况有两种不同的组件。这是你的问题的根源,因为它是从一个匿名类生成的编译器生成的类是内部。这就是为什么你得到 MethodAccessException 例外。所以你需要使用 InternalsVisibleToAttribute 使这行得通。这 SO质疑包含内部类型和反射更多的信息。

I guess that your ToSimplePropertyDictionary method and the actual usage are in two separate assemblies. This is the source of your problem because the compiler generated class which is generated from an anonymous class is internal. That is why you get the MethodAccessException exception. So you need to use the InternalsVisibleToAttribute to make it work. This SO question contains more info about internal types and reflection.

这篇关于匿名类型和获取访问的WP7.1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆