Reflection failed for properties on anonymous types in Silverlight
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 = anon开发者_Go百科ymousType.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.
I found a very good article that solved my problem. "This article explains why C# 4.0's dynamic features don't seem to work when evaluating instances of anonymous types returned from a public method of a different assembly." and thanks ligaz for a good starting point.
Anonymous Types are Internal, C# 4.0 & Silverlight
精彩评论