Get the name of a field from a class without an instance

爷,独闯天下 提交于 2019-12-05 03:27:54

I have two methods I use to do this.

The first is an extension method that can be used on any object.

public static string GetPropertyName<TEntity, TProperty>(this TEntity entity, Expression<Func<TEntity, TProperty>> propertyExpression)
{
    return propertyExpression.PropertyName();
}

Which is used like

public CoolCat Jimmy = new CoolCat();
string JimmysKaratePowerField = Jimmy.GetPropertyName(j => j.KaratePower);

The second I use when I don't have an object.

public static string PropertyName<T>(this Expression<Func<T, object>> propertyExpression)
{
        MemberExpression mbody = propertyExpression.Body as MemberExpression;

        if (mbody == null)
        {
            //This will handle Nullable<T> properties.
            UnaryExpression ubody = propertyExpression.Body as UnaryExpression;

            if (ubody != null)
            {
                mbody = ubody.Operand as MemberExpression;
            }

            if (mbody == null)
            {
                throw new ArgumentException("Expression is not a MemberExpression", "propertyExpression");
            }
        }

        return mbody.Member.Name;
}

This can be used like so

string KaratePowerField = Extensions.PropertyName<CoolCat>(j => j.KaratePower);

What you're trying to do is one of the reasons Microsoft created System.Reflection Try this:

using System.Reflection;  // reflection namespace

public static List<Type> GetClassPropertyNames(Type myClass)
        {
            PropertyInfo[] propertyInfos;
            propertyInfos = myClass.GetProperties(BindingFlags.Public);

            List<Type> propertyTypeNames = new List<Type>();

            // write property names
            foreach (PropertyInfo propertyInfo in propertyInfos)
            {
                propertyTypeNames .Add(propertyInfo.PropertyType);
            }

            return propertyNames;

        }

I believe using Reflection will be useful here. I do not have VS with me right now, but I'm sure you can do something like typeof(class).GetMembers(). My reflection is a little rusty.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!