Pobranie nazwy właściwości z obiektu

        
        public static string GetName<T>(Expression<Func<T, object>> expression) 
        {
            ExpressionType type = expression.Body.NodeType;

            if (type == ExpressionType.MemberAccess)
                return ((MemberExpression)expression.Body).Member.Name;

            if (type == ExpressionType.Convert)
                return ((MemberExpression)((UnaryExpression)expression.Body).Operand).Member.Name;

            if (type == ExpressionType.Call)
                return ((MethodCallExpression)expression.Body).Method.Name;

            throw new ArgumentException("Unknown expression type: " + type);
        }

… i użycie

var propertyName = NameHelper.GetName<Customer>(s => s.CustomerId);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s