Get All Properties Which Marked Certain Attribute

Get all properties which marked certain attribute

It's probably easiest to use IsDefined:

var properties = type.GetProperties()
.Where(prop => prop.IsDefined(typeof(LocalizedDisplayNameAttribute), false));

To get the values themselves, you'd use:

var attributes = (LocalizedDisplayNameAttribute[]) 
prop.GetCustomAttributes(typeof(LocalizedDisplayNameAttribute), false);

Reflection - Get all properties values which marked certain attribute

Not shure what result you are trying to get but this should help:

        RspServer server = new RspServer();

Type ClassType = server.GetType();

Dictionary<string, string> Description2Value = new Dictionary<string, string>();

foreach (PropertyInfo pi in ClassType.GetProperties().Where(pi => Attribute.IsDefined(pi, typeof(Description))))
{
Description d = (Description)pi.GetCustomAttributes(typeof(Description), false)[0];
string PropVal = (string)pi.GetValue(server);

Description2Value.Add(d.Value, PropVal);
}

How to get a list of properties with a given attribute?

var props = t.GetProperties().Where(
prop => Attribute.IsDefined(prop, typeof(MyAttribute)));

This avoids having to materialize any attribute instances (i.e. it is cheaper than GetCustomAttribute[s]().

Get All properties that has a custom attribute with specific values

List<PropertyInfo> result =
typeof(ClassWithCustomAttributecs)
.GetProperties()
.Where(
p =>
p.GetCustomAttributes(typeof(UseInReporte), true)
.Where(ca => ((UseInReporte)ca).Use)
.Any()
)
.ToList();

Of course typeof(ClassWithCustomAttributecs) should be replaced with an actual object you are dealing with.

Get all properties marked with [JsonIgnore] attribute

typeof(MyClass).GetProperties()
.Where(property =>
property.GetCustomAttributes(false)
.OfType<JsonIgnoreAttribute>()
.Any()
);

Specifying the type in the GetCustomAttibutes call can be more performant, in addition, you might want the logic to be reusable so you could use this helper method:

static IEnumerable<PropertyInfo> GetPropertiesWithAttribute<TType, TAttribute>()
{
Func<PropertyInfo, bool> matching =
property => property.GetCustomAttributes(typeof(TAttribute), false)
.Any();

return typeof(TType).GetProperties().Where(matching);
}

Usage:

var properties = GetPropertyWithAttribute<MyClass, JsonIgnoreAttribute>();

EDIT:
I'm not sure, but you might be after the properties without the attribute, so you could just negate the find predicate:

static IEnumerable<PropertyInfo> GetPropertiesWithoutAttribute<TType, TAttribute>()
{
Func<PropertyInfo, bool> matching =
property => !property.GetCustomAttributes(typeof(TAttribute), false)
.Any();

return typeof(TType).GetProperties().Where(matching);
}

Or you could use simple libraries such as Fasterflect:

typeof(MyClass).PropertiesWith<JsonIgnoreAttribute>();

Recursively get properties marked with an attribute

You could use this

Updated in regards to some great points in the comments from @pinkfloydx33

public static IEnumerable<(Type Class, PropertyInfo Property)> GetAttributeList<T>(Type type, HashSet<Type> visited = null)
where T : Attribute
{

// keep track of where we have been
visited = visited ?? new HashSet<Type>();

// been here before, then bail
if (!visited.Add(type))
yield break;

foreach (var prop in type.GetProperties())
{
// attribute exists, then yield
if (prop.GetCustomAttributes<T>(true).Any())
yield return (type, prop);

// lets recurse the property type as well
foreach (var result in GetAttributeList<T>(prop.PropertyType, visited))
yield return (result);
}
}

Usage

foreach (var result in GetAttributeList<FooAttribute>(typeof(Customer)))
Console.WriteLine($"{result.Class} {result.Property.Name}");

Output

ConsoleApp.Customer Name
ConsoleApp.Account Info

How to get a list of properties with a given attribute?

var props = t.GetProperties().Where(
prop => Attribute.IsDefined(prop, typeof(MyAttribute)));

This avoids having to materialize any attribute instances (i.e. it is cheaper than GetCustomAttribute[s]().

C# reflection get all property information inside the proerperties with custom attribute

You can write a method like this :

private static IEnumerable<PropInfo> GetPropertiesInfo(object obj, string route = "")
{
List<PropInfo> results = new List<PropInfo>();

// You can filter wich property you want https://learn.microsoft.com/en-us/dotnet/api/system.reflection.propertyinfo?view=net-6.0
var objectProperties = obj.GetType().GetProperties().Where(p => p.CanRead);
foreach (var property in objectProperties)
{
var value = property.GetValue(obj);

if (property.PropertyType.IsClass && property.PropertyType != typeof(string))
{
results.AddRange(GetPropertiesInfo(value, route + property.Name + "."));
}
else
{
// Check if the property has the Custom Attribute
var customAttributes = property.GetCustomAttributes<CustomAttribute>();
if (!customAttributes.Any())
continue;
// You can set a method in your Attribute : customAttributes.First().CheckIfNeedToStoreProperty(obj);

results.Add(new PropInfo()
{
PropertyName = property.Name,
Value = value,
Route = route + property.Name
});
}

}

return results;
}

public class PropInfo
{
public string PropertyName { get; set; }
public object Value { get; set; }
public string Route { get; set; }
}

public class CustomAttribute : Attribute
{
public bool CheckIfNeedToStoreProperty(object obj)
{
return true;
}
}

C# reflection get all property information inside the proerperties with custom attribute

You can write a method like this :

private static IEnumerable<PropInfo> GetPropertiesInfo(object obj, string route = "")
{
List<PropInfo> results = new List<PropInfo>();

// You can filter wich property you want https://learn.microsoft.com/en-us/dotnet/api/system.reflection.propertyinfo?view=net-6.0
var objectProperties = obj.GetType().GetProperties().Where(p => p.CanRead);
foreach (var property in objectProperties)
{
var value = property.GetValue(obj);

if (property.PropertyType.IsClass && property.PropertyType != typeof(string))
{
results.AddRange(GetPropertiesInfo(value, route + property.Name + "."));
}
else
{
// Check if the property has the Custom Attribute
var customAttributes = property.GetCustomAttributes<CustomAttribute>();
if (!customAttributes.Any())
continue;
// You can set a method in your Attribute : customAttributes.First().CheckIfNeedToStoreProperty(obj);

results.Add(new PropInfo()
{
PropertyName = property.Name,
Value = value,
Route = route + property.Name
});
}

}

return results;
}

public class PropInfo
{
public string PropertyName { get; set; }
public object Value { get; set; }
public string Route { get; set; }
}

public class CustomAttribute : Attribute
{
public bool CheckIfNeedToStoreProperty(object obj)
{
return true;
}
}

Is there a way to mark properties of an object so they will stand out in reflection?

I want to be able to act on the data members of B only, i.e to mark them so I'll be able to tell them apart from the members of A.

You can use custom attributes to add metadata to members, but it's not needed for what you want. You can use straight reflection. Look at DeclaringType, and use typeof(B) if you don't want to create an instance:

var x = typeof(B).GetProperties();
foreach (PropertyInfo i in x)
{
if (i.DeclaringType == typeof(B))
{
Console.WriteLine(i.Name);
}
}

you can also apply that filter when getting the properties:

var x = typeof(B).GetProperties(BindingFlags.DeclaredOnly
| BindingFlags.Public
| BindingFlags.Instance);
foreach (PropertyInfo i in x)
{
Console.WriteLine(i.Name);
}


Related Topics



Leave a reply



Submit