1

我正在将 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);
        }
    }

4

2 回答 2

8

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

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

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

希望这可以帮助。

于 2010-09-03T08:47:12.727 回答
1

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

匿名类型为内部、C# 4.0 和 Silverlight

于 2010-09-03T19:42:57.373 回答