ozsenegal
ozsenegal

Reputation: 4133

C# reflection avoid propertie

Im using reflection to acess a class tha represents a table in DB.However,reflection read all properties of that class,and im wondering if there're some atributte in c# we can use to avoid read that propertie.

i.e:

[AvoidThisPropertie]
public string Identity
{
get;
set;
}

Upvotes: 0

Views: 209

Answers (2)

Aren
Aren

Reputation: 55946

PropertyInfo [] properties = MyType.GetProperties(
    BindingFlags.Instance | BindingFlags.Public);

IList<PropertyInfo> crawlableProperties = properties.Where(
    p => p.GetCustomAttributes(
        typeof(AvoidThisProperty), true)
        .Count() == 0);

You'd also have to create the AvoidThisProperty

[AttributeUsage(AttributeTargets.Property)]
public class AvoidThisPropertyAttribute : Attribute
{
   // Doesn't need a body
}

You still have access to all the properties, but the LINQ statement would generate a list of the desired properties.

Upvotes: 3

abatishchev
abatishchev

Reputation: 100258

If you could avoid full accessibility, reflection would have no sense

Upvotes: 1

Related Questions