加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 17:42:27 所属栏目:百科 来源:网络整理
导读:我正在尝试写一个简单的对象到字典转换器,如下所示: public static class SimplePropertyDictionaryExtensionMethods{ public static IDictionarystring,string ToSimplePropertyDictionary(this object input) { if (input == null) return new 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()"}

这只是芒果的安全模式,说“不”?有什么办法吗?感觉这是一个公共的访问者 – 所以觉得我应该能够调用它?

斯图尔特

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读