使用lambda表达式获取属性或类型名称(Using lambda expression to get property OR type name)
当lambda表达式引用实际实例本身时,如何调整下面的方法?
例如,而不是
x => x.Name
表达是
x => x
所以,如果我有一些类“汽车”我可以返回字符串“汽车”,而不是只能操作其属性(例如Car.Colour)
方法:
public static string GetMemberName(Expression expression) { if (expression is LambdaExpression) expression = ((LambdaExpression)expression).Body; if (expression is MemberExpression) { var memberExpression = (MemberExpression)expression; if (memberExpression.Expression.NodeType == ExpressionType.MemberAccess) { return GetMemberName(memberExpression.Expression) + "." + memberExpression.Member.Name; } return memberExpression.Member.Name; } if (expression is UnaryExpression) { var unaryExpression = (UnaryExpression)expression; if (unaryExpression.NodeType != ExpressionType.Convert) throw new Exception(string.Format( "Cannot interpret member from {0}", expression)); return GetMemberName(unaryExpression.Operand); } throw new Exception(string.Format( "Could not determine member from {0}", expression)); }
即我想要的东西:
if (expression is SomeExpressionThatReturnsAnInstance) { return (name of type of instance); }
How can I adapt the method below to work when the lambda expression refers to the actual instance itself?
e.g. instead of
x => x.Name
the expression is
x => x
so if I had some class "Car" I could return the string "Car" instead of only being able to operate on its properties (e.g. Car.Colour)
The method:
public static string GetMemberName(Expression expression) { if (expression is LambdaExpression) expression = ((LambdaExpression)expression).Body; if (expression is MemberExpression) { var memberExpression = (MemberExpression)expression; if (memberExpression.Expression.NodeType == ExpressionType.MemberAccess) { return GetMemberName(memberExpression.Expression) + "." + memberExpression.Member.Name; } return memberExpression.Member.Name; } if (expression is UnaryExpression) { var unaryExpression = (UnaryExpression)expression; if (unaryExpression.NodeType != ExpressionType.Convert) throw new Exception(string.Format( "Cannot interpret member from {0}", expression)); return GetMemberName(unaryExpression.Operand); } throw new Exception(string.Format( "Could not determine member from {0}", expression)); }
i.e. I want something like:
if (expression is SomeExpressionThatReturnsAnInstance) { return (name of type of instance); }
原文:https://stackoverflow.com/questions/29788448
更新时间:2022-11-09 09:11
最满意答案
对于单选按钮,您应该使用
checked
。$(this).prop('checked')
For radio button, you should use
checked
.$(this).prop('checked')
相关问答
更多-
对于单选按钮,您应该使用checked 。 $(this).prop('checked') For radio button, you should use checked. $(this).prop('checked')
-
在你的匿名函数里面,在$('.showButton').click(function () {你可以用$(this).text(); (或$(this).html();如果你需要的话$(this).html();与它的HTML元素)。 使用此方法请参阅以下示例:: $('.showButton').click(function(){ $('#log').val($(this).text()); }); .showButton{ cursor:pointer; }