gpt4 book ai didi

c# - C# 中的表达式树和惰性求值

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

我有一小段代码,其中我采用 ParameterExpression 字符串数组并将特定索引转换为目标类型。我通过调用 Parse(如果类型是原始类型)或通过尝试原始转换(希望转换为字符串或隐式字符串)来执行此操作。

static Expression ParseOrConvert(ParameterExpression strArray, ConstantExpression index, ParameterInfo paramInfo)
{
Type paramType = paramInfo.ParameterType;

Expression paramValue = Expression.ArrayIndex(strArray, index);

if (paramType.IsPrimitive) {
MethodInfo parseMethod = paramType.GetMethod("Parse", new[] { typeof(string) });
// Fetch Int32.Parse(), etc.

// Parse paramValue (a string) to target type
paramValue = Expression.Call(parseMethod, paramValue);
}
else {
// Else attempt a raw conversion
paramValue = Expression.Convert(paramValue, paramType);
}

return paramValue;
}

这行得通,但我正在尝试重写条件。

paramValue = Expression.Condition(
Expression.Constant(paramType.IsPrimitive),
Expression.Call(parseMethod, paramValue),
Expression.Convert(paramValue, paramType)
);

这总是导致 System.InvalidOperationException,大概是因为它尝试了两种转换。我发现第二种风格写起来更直观,所以这很不幸。

我能否以将评估推迟到实际需要值时的方式来编写此代码?

最佳答案

通常调试就像新闻...在新闻中有 five Ws :什么哪里什么时候为什么(加上如何)..在编程中它是相似的。 抛出异常(即什么)?让我们让代码更容易调试:

static Expression ParseOrConvert(ParameterExpression strArray, ConstantExpression index, ParameterInfo paramInfo)
{
Type paramType = paramInfo.ParameterType;

Expression paramValue = Expression.ArrayIndex(strArray, index);
MethodInfo parseMethod = paramType.GetMethod("Parse", new[] { typeof(string) });

var isPrimitive = Expression.Constant(paramType.IsPrimitive);
var call = Expression.Call(parseMethod, paramValue);
var convert = Expression.Convert(paramValue, paramType);

var paramValue2 = Expression.Condition(
isPrimitive,
call,
convert
);

return paramValue2;
}

然后这样调用它:

public static void MyMethod(int par1)
{
}

然后

ParameterExpression strArray = Expression.Parameter(typeof(string[]));

// paramType int
var paramInfo = typeof(Program).GetMethod("MyMethod").GetParameters()[0];

var result = ParseOrConvert(strArray, Expression.Constant(0), paramInfo);

现在...抛出异常? Expression.Convert(paramValue, paramType) 抛出异常...为什么?因为你正在尝试做一个:

string paramValue = ...;
convert = (int)paramValue;

那肯定是违法的!即使是“死”代码(无法访问的代码)也必须在 .NET 中“可编译”(以其 IL 语言)。所以你的错误是试图在你的表达式中引入一些非法的死代码,那就是:

string paramValue = ...;
isPrimitive = true ? int.Parse(paramValue) : (int)paramValue;

这不会在 C# 中编译,甚至可能无法用 IL 代码编写。 Expression 类抛出它。

关于c# - C# 中的表达式树和惰性求值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51073375/

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