c# - 检查属性是否具有指定的属性,然后打印它的值

标签 c# .net

我有一个ShowAttribute,我正在使用这个属性来标记类的一些属性。我想要的是,通过具有 Name 属性的属性打印值。我怎样才能做到这一点 ?

public class Customer
{
    [Show("Name")]
    public string FirstName { get; set; }

    public string LastName { get; set; }

    public Customer(string firstName, string lastName)
    {
        this.FirstName = firstName;
        this.LastName = lastName;
    }
}

class ShowAttribute : Attribute
{
    public string Name { get; set; }

    public ShowAttribute(string name)
    {
        Name = name;
    }
}

我知道如何检查该属性是否具有 ShowAttribute,但我不明白如何使用它。

var customers = new List<Customer> { 
    new Customer("Name1", "Surname1"), 
    new Customer("Name2", "Surname2"), 
    new Customer("Name3", "Surname3") 
};

foreach (var customer in customers)
{
    foreach (var property in typeof (Customer).GetProperties())
    {
        var attributes = property.GetCustomAttributes(true);

        if (attributes[0] is ShowAttribute)
        {
            Console.WriteLine();
        }
    }
}

最佳答案

Console.WriteLine(property.GetValue(customer).ToString());

但是,这会很慢。您可以使用 GetGetMethod 改进它并为每个属性创建一个委托(delegate)。或者将带有属性访问表达式的表达式树编译成委托(delegate)。

关于c# - 检查属性是否具有指定的属性,然后打印它的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11637255/

相关文章:

.net - 日期时间格式与 SQL Server 中的格式不匹配

c# - .net 中请求不等待响应

c# - ASp.net Webform 多行文本框在页面加载时自动添加换行符

c# - WCF SOAP 服务为 HTTPS 终结点返回 404 Not Found

c# - AcceptButton不会关闭表单

c# - 后台工作人员在运行时卡住/死亡

c# - Fody PropertyChanged 干扰 FxCop

c# - Directory.CreateDirectory 是异步的还是什么?

.net - 为什么 ASP.NET 找不到 asp :UpdateProgress?

c# - 优化.NET中大系列数据的存储和处理