【问题标题】:Type does not contain a definition for 'GetProperties'类型不包含“GetProperties”的定义
【发布时间】:2023-03-19 21:35:02
【问题描述】:

我正在将库项目迁移到 .net 标准,当我尝试使用 System.Reflection API 调用 Type:GetProperties() 时出现以下编译错误:

类型不包含“GetProperties”的定义

这是我的project.json

{
  "version": "1.0.0-*",
  "buildOptions": {
    "debugType": "portable"
  },
  "dependencies": {},
  "frameworks": {
    "netstandard1.6": {
      "dependencies": {
        "NETStandard.Library": "1.6.0"
      }
    }
  }
}

我错过了什么?

【问题讨论】:

    标签: .net-core .net-standard


    【解决方案1】:

    更新:随着 .NET COre 2.0 的发布,System.Type 又回来了,所以这两个选项都可用:

    • typeof(Object).GetType().GetProperties()
    • typeof(Object).GetTypeInfo().GetProperties()

      这个需要加using System.Reflection;

    • typeof(Object).GetTypeInfo().DeclaredProperties

      请注意,此属性返回 IEnumerable<PropertyInfo>,而不是像前两个方法那样返回 PropertyInfo[]


    System.Type 上与反射相关的大多数成员现在都在System.Reflection.TypeInfo 上。

    首先调用GetTypeInfo 以从Type 获取TypeInfo 实例:

    typeof(Object).GetTypeInfo().GetProperties();
    

    另外,别忘了使用using System.Reflection;

    【讨论】:

    • 没错。但我认为你的答案有错别字。是typeof(Object).GetTypeInfo().GetProperties();
    【解决方案2】:

    在撰写本文时,GetProperties() 现在是:

    typeof(Object).GetTypeInfo().DeclaredProperties;

    【讨论】:

    • DeclaredProperties 只返回在类型本身上声明的属性,不包括从父类继承的属性
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多