10

我正在尝试向 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 访问器 - 所以感觉我应该能够调用它?

斯图尔特

4

2 回答 2

8

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

于 2011-11-25T19:44:49.270 回答
1

删除 BindingFlags.GetProperty

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

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

var value = propertyInfo.GetValue(input, null);
var value = propertyInfo.GetGetMethod().Invoke(input, null); 
于 2011-11-25T19:36:44.843 回答