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()"}
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?
Stuart
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…