Object - GetProperty
An object extension method that gets the properties.
public static void Main() { //C# Extension Method: Object - GetProperty PropertyInfo PublicProperty = typeof(PropertyModel<int>).GetProperty("PublicProperty", BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); PropertyInfo ProtectedInternalProperty = typeof(PropertyModel<int>).GetProperty("ProtectedInternalProperty", BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); PropertyInfo AbstractProperty = typeof(PropertyModel<int>).GetProperty("AbstractProperty", BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); Console.WriteLine(PublicProperty.GetDeclaraction()); Console.WriteLine(ProtectedInternalProperty.GetDeclaraction()); Console.WriteLine(AbstractProperty.GetDeclaraction()); } public class PropertyModel<T> : AbstractPropertyModel { public static int StaticProperty { get; set; } public override int OverrideProperty { get; set; } public virtual int VirtualProperty { get; set; } internal int InternalProperty { get; set; } private int PrivateProperty { get; set; } protected int ProtectedProperty { get; set; } protected internal int ProtectedInternalProperty { get; set; } public int PublicProperty { get; set; } public int PublicGetterPrivateSetterProperty { get; private set; } public int PrivateGetterPublicSetterProperty { private get; set; } public T GenericProperty { get; set; } public T this[T param1, int param2] { get { return param1; }} public override int AbstractProperty { get; set; } } public abstract class AbstractPropertyModel { public abstract int AbstractProperty { get; set; } public virtual int OverrideProperty { get; set; } }
View Source
using System.Reflection; public static partial class Extensions { /// <summary> /// A T extension method that gets a property. /// </summary> /// <typeparam name="T">Generic type parameter.</typeparam> /// <param name="this">The @this to act on.</param> /// <param name="name">The name.</param> /// <returns>The property.</returns> public static PropertyInfo GetProperty<T>(this T @this, string name) { return @this.GetType().GetProperty(name); } /// <summary> /// A T extension method that gets a property. /// </summary> /// <typeparam name="T">Generic type parameter.</typeparam> /// <param name="this">The @this to act on.</param> /// <param name="name">The name.</param> /// <param name="bindingAttr">The binding attribute.</param> /// <returns>The property.</returns> public static PropertyInfo GetProperty<T>(this T @this, string name, BindingFlags bindingAttr) { return @this.GetType().GetProperty(name, bindingAttr); } }