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/

相关文章:

c# - gridview 完全完成后是否有调用的事件?

.net - HTML 页面与 MVC 中的 razor 引擎布局 View 集成

c# - 调用 BitmapDecoder.CreateAsync(stream) 时 WinRT 应用程序挂起

c# - 修改 PropertyGrid 和 TypeConverterAttribute 的默认行为

C# - 对象组合 - 删除样板代码

.net - 如何阻止 .NET WebBrowser 控件中的下载?

.net - 如何索引 HTML 文档?

c# - 在代码中为合法状态抛出异常

c# - 在屏幕上绘制位图图像

c# - DropDownList 项目在每次回发后重复其值