【问题标题】:How to get property of a class in Asp.net Core [duplicate]如何在 Asp.net Core 中获取类的属性 [重复]
【发布时间】:2017-01-21 15:45:47
【问题描述】:

我有一个模型:

public class Message
{
    public string CustomerName { get; set; }
    public DateTime Date { get; set; }
    public string RegistrationCode { get; set; }
}

我想动态获取它的属性,在之前版本的.Net 中我们通过:obj.GetType().GetProperties(); 来实现,但在.Net Core 中我们没有.GetProperties(),我该怎么做?

【问题讨论】:

  • 试试obj.GetType().GetTypeInfo().DeclaredProperties
  • 使用 System.Reflection;编写的代码是正确的,不需要额外的包。

标签: asp.net-core


【解决方案1】:

您可能错过了添加以下 using 语句:

using System.Reflection;

我尝试运行以下控制台应用程序(我认为您不会注意到 asp.net 核心项目中的任何差异):

using System;
using System.Reflection;

namespace ConsoleApp1
{
    public class Message
    {
        public string CustomerName { get; set; }
        public DateTime Date { get; set; }
        public string RegistrationCode { get; set; }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            var obj = new Message();
            var properties = obj.GetType().GetProperties();
            Console.ReadKey();
        }
    }
}

我没有注意到任何问题。下面是 project.json 供参考:

{
  "version": "1.0.0-*",
  "buildOptions": {
    "emitEntryPoint": true
  },

  "dependencies": {
    "Microsoft.NETCore.App": {
      "type": "platform",
      "version": "1.0.1"
    }
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": "dnxcore50"
    }
  }
}

您确定您使用的是最新的 .net 核心版本吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-28
    • 1970-01-01
    • 1970-01-01
    • 2015-09-30
    • 2019-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多