alielie
2026-09-10 9ec80cafc23f5ee3278cacce3c9f86f4087b435a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using System;
using System.Linq.Expressions;
using DynamicExpresso.Parsing;
using DynamicExpresso.Reflection;
 
namespace DynamicExpresso.Resolution
{
    internal static class ExpressionUtils
    {
        public static Expression PromoteExpression(Expression expr, Type type)
        {
            if (expr.Type == type)
                return expr;
 
            if (expr is ConstantExpression ce && ce == ParserConstants.NullLiteralExpression)
            {
                if (type.ContainsGenericParameters)
                    return null;
                if (!type.IsValueType || TypeUtils.IsNullableType(type))
                    return Expression.Constant(null, type);
            }
 
            if (expr is InterpreterExpression ie)
            {
                if (!ie.IsCompatibleWithDelegate(type))
                    return null;
 
                if (!type.ContainsGenericParameters)
                    return ie.EvalAs(type);
 
                return expr;
            }
 
            if (type.IsAssignableFrom(expr.Type))
            {
                return Expression.Convert(expr, type);
            }
 
            if (type.IsGenericType && !TypeUtils.IsNumericType(type))
            {
                var genericType = TypeUtils.FindAssignableGenericType(expr.Type, type);
                if (genericType != null)
                    return Expression.Convert(expr, genericType);
            }
 
            if (TypeUtils.IsCompatibleWith(expr.Type, type))
            {
                return Expression.Convert(expr, type);
            }
 
            return null;
        }
    }
}