Getting sub property names strongly typed

前端 未结 2 1219
自闭症患者
自闭症患者 2021-01-16 06:40

With databinding objects to controls and grids I hated how the property names would be magic strings, so I created a very simple method as follows:

public st         


        
2条回答
  •  不思量自难忘°
    2021-01-16 07:07

    I came up with the following which seems to work:

    public static string GetComplexPropertyName(Expression> expressionForProperty)
    {
        // get the expression body
        Expression expressionBody = expressionForProperty.Body as MemberExpression;
    
        string expressionAsString = null;
    
        // all properties bar the root property will be "convert"
        switch (expressionBody.NodeType)
        {
            case ExpressionType.Convert:
            case ExpressionType.ConvertChecked:
    
                UnaryExpression unaryExpression = expressionBody as UnaryExpression;
    
                if (unaryExpression != null)
                {
                    expressionAsString = unaryExpression.Operand.ToString();
                }
    
                break;
            default:
                expressionAsString = expressionBody.ToString();
                break;
        }
    
        // makes ure we have got an expression
        if (!String.IsNullOrWhiteSpace(expressionAsString))
        {
            // we want to get rid of the first operand as it will be the root type, so get the first occurence of "."
            int positionOfFirstDot = expressionAsString.IndexOf('.');
    
            if (positionOfFirstDot != -1)
            {
                return expressionAsString.Substring(positionOfFirstDot + 1, expressionAsString.Length - 1 - positionOfFirstDot);
            }
        }
    
        return string.Empty;
    }
    

提交回复
热议问题