【问题标题】:Reflection failed for properties on anonymous types in SilverlightSilverlight 中匿名类型的属性的反射失败
【发布时间】:2010-09-03 07:17:04
【问题描述】:

我在 VS 2010 中使用 Silverlight 4 并尝试对匿名类型进行反射,但我得到了一些“尝试通过方法 '...' 访问方法 '...' 失败。”。我为此尝试了各种解决方法,但找不到简单的解决方法。

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);
        }
    }

【问题讨论】:

    标签: c# silverlight reflection anonymous-types propertyinfo


    【解决方案1】:

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

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

    您目前可以做的是调用匿名对象ToString() 方法并从字符串表示中提取值。

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      我发现一篇很好的文章解决了我的问题。 “这篇文章解释了为什么 C# 4.0 的动态特性在评估从不同程序集的公共方法返回的匿名类型的实例时似乎不起作用。”并感谢 ligaz 提供了一个良好的起点。

      Anonymous Types are Internal, C# 4.0 & Silverlight

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多