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