c# - 获取对象的属性名称和它期望的类型

标签 c# .net reflection types

我怎样才能得到一个对象的所有属性名称和它期望的值类型?

假设我有这两个实体类:

public class Blog 
{ 
    public int Id { get; set; } 
    public string Title { get; set; } 
    public string BloggerName { get; set;} 
    public Post Post { get; set; } 
} 

public class Post 
{ 
    public int Id { get; set; } 
    public string Title { get; set; } 
    public DateTime DateCreated { get; set; } 
    public string Content { get; set; } 
    public int BlogId { get; set; } 
    public Comment Comment { get; set; } 
}

我怎样才能得到这个结果:

  • “Blog.Id 需要一个整数”
  • “Blog.Title 需要一个字符串”
  • “Blog.BloggerName 需要一个字符串”
  • “Post.Id 需要一个整数”
  • “Post.Title 需要一个字符串”
  • “Post.DateCreated 需要一个字符串”
  • 等...

我知道这可以一次完成一个属性,但是有没有更优雅的方法来做到这一点,因为实体类有很多属性(并且它们从类型改变,因为它仍在开发中)并且有复杂的对象我也想这样做?

编辑,这需要递归完成。刚好路过Blog不知道它是否包含另一个用户定义的对象,如 Post , 不是我要找的。

最佳答案

当然要使用反射。

foreach (PropertyInfo p in typeof(Blog).GetProperties())
{
    string propName = p.PropertyType.Name;
    Console.WriteLine("Property {0} expects {1} {2}",
        p.Name,
        "aeiou".Contains(char.ToLower(propName[0])) ? "an" : "a",
        propName);
}

请注意 GetProperties还有一个接受 BindingFlags 的重载,它只允许您获取一些属性,例如实例/静态公共(public)/私有(private)。


下面是一个理论上如何递归工作的示例,尽管即使在这个简单的示例中,这也会创建一个 StackOverflowException,因为 DateTime 具有本身为 DateTimes.

void ListProperties(Type t)
{
    foreach (PropertyInfo p in t.GetProperties())
    {
        string propName = p.PropertyType.Name;
        Console.WriteLine("Property {0} expects {1} {2}",
            p.Name,
            "aeiou".Contains(char.ToLower(propName[0])) ? "an" : "a",
            propName);
        ListProperties(p.PropertyType);
    }
}

ListProperties(typeof(Blog));

关于c# - 获取对象的属性名称和它期望的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28011528/

相关文章:

scala - 是否可以将 TypeTag 转换为 Manifest?

c# - 如何将字符串放在字符的右侧?

c# - 在正文中使用 int/string (简单类型)发布到 asp.net core web api 2.1 不起作用

c# - 我应该有返回 Disposable 实例列表的方法吗?

java - 比较几个 javabean 属性的最佳方法是什么?

java - 如何仅获取 java 类的 protected 和公共(public)构造函数?

c# - 在哪里可以找到用简码定义的美国所有州的类?

c# - 在泛型 (Y) 方法中使用泛型 (X) 委托(delegate),其中 Y 扩展了一些基类。无法转换为基类

c# - 从 C#.net 导出 SAS .XPT 文件

c# - 即使控制台不可见,Console.WriteLine 是否会导致性能下降? (C#)