[英]C# Generic Method: how to declare this kind?
I want to be able to call this method like this:我希望能够像这样调用这个方法:
test.TestMethod<From, To>(to => to.Prop1);
and have IDE auto-complete properties from To.并具有来自 To 的 IDE 自动完成属性。 In TestMethod
, I want to pull the name of the property.在TestMethod
,我想提取属性的名称。 In this case Prop1
.在这种情况下Prop1
。 It seems like its kind of working, but I'm not sure about the Expression<Func<TTo, object>>
, especially the object part.这似乎是一种工作,但我不确定Expression<Func<TTo, object>>
,尤其是对象部分。
public class Test
{
public void TestMethod<TFrom, TTo>(Expression<Func<TTo, object>> p)
{
}
}
It does what its supposed to now if I recurse through p, I can get to the name, but it doesn't look right to me, especially since pulling the name of the prop looks like:如果我通过 p 递归,它现在会做它应该做的事情,我可以得到这个名字,但对我来说它看起来不正确,特别是因为拉取道具的名字看起来像:
((MemberExpression)((UnaryExpression)(((LambdaExpression)p).Body)).Operand)).Member.Name
Any way to do this cleaner?有什么办法可以做这个清洁工吗?
Here is a helper class that will inspect the expression and extract the member info of the property这是一个帮助类,它将检查表达式并提取属性的成员信息
using System.Linq.Expressions;
using System.Reflection;
/// <summary>
/// Extension for <see cref="Expression"/>.
/// </summary>
public static class ExpressionExtensions {
/// <summary>
/// Converts an expression into a <see cref="System.Reflection.MemberInfo"/>.
/// </summary>
/// <param name="expression">The expression to convert.</param>
/// <returns>The member info.</returns>
public static MemberInfo GetMemberInfo(this Expression expression) {
var lambda = (LambdaExpression)expression;
MemberExpression memberExpression;
if (lambda.Body is UnaryExpression) {
var unaryExpression = (UnaryExpression)lambda.Body;
memberExpression = (MemberExpression)unaryExpression.Operand;
}
else
memberExpression = (MemberExpression)lambda.Body;
return memberExpression.Member;
}
}
with that you can then extract the name as intended...有了它,您就可以按预期提取名称...
public class Test {
public void TestMethod<TFrom, TTo>(Expression<Func<TTo>> property) {
var memberName = property.GetMemberInfo().Name;
//...other code
}
}
You will then be able to call this method like this...然后你就可以像这样调用这个方法......
test.TestMethod<From, To>(to => to.Prop1);
...and get the property name. ...并获取属性名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.