Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous types and Get accessors on WP7.1?

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

like image 534
Stuart Avatar asked Nov 25 '11 19:11

Stuart


2 Answers

I guess that your ToSimplePropertyDictionary method and the actual usage are in two separate assemblies. This is the source of your problem because the compiler generated class which is generated from an anonymous class is internal. That is why you get the MethodAccessException exception. So you need to use the InternalsVisibleToAttribute to make it work. This SO question contains more info about internal types and reflection.

like image 111
nemesv Avatar answered Oct 04 '22 03:10

nemesv


Remove BindingFlags.GetProperty

This is used to get a property value when using InvokeMember, it does not specify that you want a read only property returned.

EDIT: The problem may actually be with the propertyInfo.GetGetMethod() - Try using one of the following (I have only ever used the first one):

var value = propertyInfo.GetValue(input, null);
var value = propertyInfo.GetGetMethod().Invoke(input, null); 
like image 42
calum Avatar answered Oct 04 '22 02:10

calum