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 } }
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)));
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!