Use Reflection to get PropertyInfo, only want to see accessors that have mutators

StackOverflow https://stackoverflow.com/questions/8867967

  •  16-04-2021
  •  | 
  •  

Question

Using reflection I want to retrieve only the properties that have both a get and a set method, and ignore ones with only a get. What I'm trying to do is give the user a list of variables that he/she is able to change, so showing them properties that only have a get method is misleading.

Given this code below, the user would only be shown Name. Or I could possibly show them both, but grey-out UniqueID so they know they cannot change it.

public Int64 UniqueID
{
    get { return this.uniqueID; }
}

public String Name
{
    get { return this.name; }
    set { this.name = value; }
}

Background Info: I'm using C# 4.0.

Était-ce utile?

La solution

You can use the CanRead and CanWrite properties:

Type type = ...
var readWriteProps = type.GetProperties()
                         .Where(p => p.CanRead && p.CanWrite); 

Do note that the above query looks only for public properties with public accessors.

Autres conseils

I think the property you are looking for is PropertyInfo.CanWrite and this can be implemented as the following to check both Get and Set with something like:

if (propInfo.CanWrite && propInfo.CanRead)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top