我正在尝试写一个简单的对象到字典转换器,如下所示:
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包含有关内部类型和反射的更多信息.