I'm using Silverlight 4 with VS 2010 and trying to do reflection on anonymous type and I got some "Attempt by method '...' to access method '...' failed.". I tried various workarounds for this but I couldn't find and simple ones.
class.CallAnonymous("SimpleClass", "HelloFunc", new { strIn = "Boo" });
public void CallAnonymous(string cName, string cAction, object anonymousParms)
{
Type anonymousType = anonymousParms.GetType();
PropertyInfo[] props = anonymousType.GetProperties();
ServiceParam serviceParam = new ServiceParam();
foreach (var info in props)
{
string propertyName = info.Name;
object propertyObj = info.GetValue(anonymousParms, null);
// Throw the exception on PropertyInfo.GetValue()
serviceParam.Add(propertyName, propertyObj);
}
}
[Edit] You can actually bind to an anonymous type by applying [assembly: InternalsVisibleTo("System.Windows")] assembly level attribute in your projects. This will enable Silverlight's data binding system to see those compiler-generated internal types.
Unfortunately you cannot access anonymous object properties, because the compiler marks them as internal and the Silverlight security sandbox prevents you from accessing internal members.
What you can do currently is call the anonymous object ToString()
method and extract the values from the string representation.
Hope this helps.