Home > Backend Development > C++ > How Can I Efficiently Get a List of Properties with a Specific Non-Multiple Attribute?

How Can I Efficiently Get a List of Properties with a Specific Non-Multiple Attribute?

Barbara Streisand
Release: 2025-01-03 05:57:42
Original
388 people have browsed it

How Can I Efficiently Get a List of Properties with a Specific Non-Multiple Attribute?

Getting a Property List with a Specific Attribute

In order to retrieve a list of public properties that possess a certain attribute marked as non-multiple (AllowMultiple attribute set to false), a common approach is to loop through the properties and check for the attribute's presence.

foreach (var property in t.GetProperties())
{
    var attributes = property.GetCustomAttributes(typeof(MyAttribute), true);
    if (attributes.Length == 1)
    {
        // Property with custom attribute
    }
}
Copy after login

However, an optimized way to achieve the same result is to utilize LINQ's where clause along with Attribute.IsDefined() as seen below:

var properties = t.GetProperties().Where(
    property => Attribute.IsDefined(property, typeof(MyAttribute)));
Copy after login

This alternative method bypasses the need to create attribute instances, resulting in a more efficient approach.

The above is the detailed content of How Can I Efficiently Get a List of Properties with a Specific Non-Multiple Attribute?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template