Silverlight中匿名类型的属性反射失败

bmu*_*ata 1 c# reflection silverlight anonymous-types propertyinfo

我正在使用Silverlight 4和VS 2010并试图对匿名类型进行反思,我得到了一些"尝试方法'......'来访问方法'......'失败了." 我为此尝试了各种解决方法,但我找不到简单的解决方法.

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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

lig*_*gaz 8

[编辑]您可以通过在项目中应用[assembly:InternalsVisibleTo("System.Windows")]程序集级别属性来实际绑定到匿名类型.这将使Silverlight的数据绑定系统能够查看那些编译器生成的内部类型.

遗憾的是,您无法访问匿名对象属性,因为编译器将它们标记为内部属性,而Silverlight安全沙箱会阻止您访问内部成员.

您当前可以执行的操作是调用匿名对象ToString()方法并从字符串表示中提取值.

希望这可以帮助.