【问题标题】:Missing Type.GetProperty() method in Windows 8 Developer PreviewWindows 8 Developer Preview 中缺少 Type.GetProperty() 方法
【发布时间】:2016-10-05 06:09:50
【问题描述】:

我正在尝试将一个简单的应用程序移植到 Windows 8 Metro (WinRT)。似乎缺少一些非常基本的方法。一个基本示例:Type.GetProperty()。它适用于 Windows Phone 7、Silverlight 和 .NET 客户端配置文件。我必须安装一些东西(例如一个特殊的库)还是这种方法在 .NET Metro 配置文件中根本不可用?

更新

好的,谢谢。现在我使用this.GetType().GetTypeInfo().DeclaredProperties

using System.Reflection; 需要有这个GetTypeInfo() 扩展方法。

【问题讨论】:

  • 旁注:将现有的 WP7 应用程序移植到 Metro 并不是那么简单。不仅有命名空间的变化……(Reflection、Streams、Dispatcher……)

标签: c# reflection windows-8 windows-runtime microsoft-metro


【解决方案1】:

Metro 中的反射发生了一些变化:请参阅MSDN(“反射变化” - 靠近底部)。

基本上,您现在需要:type.GetTypeInfo()

【讨论】:

    【解决方案2】:

    除了 Nicholas Butler 的回应,我最终使用了这种扩展来维护代码在所有平台上的可重用性。

    #if NETFX_CORE // Workaround for .Net for Windows Store not having Type.GetProperty method
        public static class GetPropertyHelper
        {
            public static PropertyInfo GetProperty(this Type type, string propertyName)
            {
                return type.GetTypeInfo().GetDeclaredProperty(propertyName);
            }
        }
    #endif
    

    这样,Type.GetProperty() 就适用于所有平台。

    【讨论】:

    • 当然,这是一个旧线程,但我想补充一点,GetDeclaredPropert(y/ies) 只会返回当前类型的属性。这意味着如果 Class2 派生自 Class1,GetDerivedProperties 将只返回 Class2 的属性。
    • @BjarkeSøgaard 如果你想搜索所有属性,你可以使用type.GetRuntimeProperty(propertyName)
    • 实际上我最终只是这样做了:for (; type != null; type = type.GetTypeInfo().BaseType)
    • GetProperties() 怎么样?
    • @BjarkeSøgaard 你试过GetType().GetRuntimeProperties()吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-10
    • 1970-01-01
    • 2013-10-22
    • 1970-01-01
    相关资源
    最近更新 更多