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

查看:14
本文介绍了匿名类型和 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()"}

这只是 Mango 上的安全模型说不"吗?有什么办法可以解决吗?感觉这是一个公共的 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 方法和实际用法是在两个独立的程序集中.这是您的问题的根源,因为从匿名类生成的编译器生成的类是 internal.这就是您收到 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天全站免登陆