gpt4 book ai didi

c# - 使用反射将 ParameterExpression 转换为对象

转载 作者:太空宇宙 更新时间:2023-11-03 13:09:57 25 4
gpt4 key购买 nike

我想从 ParameterExpression 类中转换任何对象。

这是示例代码(伪造我想说的):

public void Execute(Expression<Action<TService>> operation)
{
try
{

var param = operation.Parameters[0]; //myparameter to cast
var obj = param as AnyCastObject; // I want to cast
DoSomething(obj); // and do something this object without losing any assigned propery.

operation.Compile().Invoke(OpenNewChannel);
}
finally
{
CloseChannel();
}
}

编辑:

这是我的方法体:

执行(x => x.UserAuthentication(requestDto));

我想操作requestDto。

最佳答案

在这里...有了它,您应该能够提取您的requestDto

请注意,调用编译表达式时不需要 Invoke()

operation.Compile()(OpenNewChannel);

足够了。

现在,提取requestDto:

// Works for Execute(x => x.UserAuthentication(something))
// where something must be a constant value, a variable,
// a field, a property
var param = operation.Parameters[0]; //myparameter to cast

var body = operation.Body as MethodCallExpression;

if (body == null || body.Object != param || body.Method.Name != "UserAuthentication")
{
throw new NotSupportedException();
}

// If you have a type for the parameter, replace it here:
// object -> yourtype
object requestValue;

var constantExpression = body.Arguments[0] as ConstantExpression;

if (constantExpression == null)
{
// For nearly all the types of expression, the only way
// to extract the final value is to compile them and then
// execute them (the execution is the last "()" )

// If you have a type for the parameter, replace it here:
// Func<object> -> Func<yourtype>
requestValue = Expression.Lambda<Func<object>>(body.Arguments[0]).Compile()();
}
else
{
// Constant expression values can be directly extracted

// If you have a type for the parameter, replace it here:
// (yourtype)constantExpression.Value
requestValue = constantExpression.Value;
}

关于c# - 使用反射将 ParameterExpression 转换为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29364147/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com