I am trying to reflect over a type, and get only the properties with public setters. This doesn't seem to be working for me. In the example LinqPad script below, 'Id' and 'InternalId' are returned along with 'Hello'. What can I do to filter them out开发者_Go百科?
void Main()
{
typeof(X).GetProperties(BindingFlags.SetProperty | BindingFlags.Public | BindingFlags.Instance)
.Select (x => x.Name).Dump();
}
public class X
{
public virtual int Id { get; protected set;}
public virtual int InternalId { get; protected internal set;}
public virtual string Hello { get; set;}
}
You can use the GetSetMethod() to determine whether the setter is public or not.
For example:
typeof(X).GetProperties(BindingFlags.SetProperty |
BindingFlags.Public |
BindingFlags.Instance)
.Where(prop => prop.GetSetMethod() != null)
.Select (x => x.Name).Dump();
The GetSetMethod()
returns the public setter of the method, if it doesn't have one it returns null
.
Since the property may have different visibility than the setter it is required to filter by the setter method visibility.
精彩评论