Код: Выделить всё
Exception thrown: 'System.ArgumentException' in System.Linq.Expressions.dll Expression of type 'System.Void' cannot be used for return type 'TestDatabase.Models.TestEnum'
Оригинал метод, который я пытаюсь воссоздать в виде дерева выражений:
Код: Выделить всё
private TEnum ConvertStringToEnum(TDbValueType dbValue)
{
if (Enum.IsDefined(typeof(TEnum), dbValue))
{
return (TEnum)Enum.Parse(typeof(TEnum), (string)(object)dbValue);
}
throw new Exception("");
}
Код: Выделить всё
public static Func BuildStringToEnumConvertor()
{
var enumType = typeof(TEnum);
var enumTypeExp = Expression.Constant(enumType);
//var labeleExp = Expression.Label(enumType);
var dbValueExp = Expression.Parameter(typeof(TString), "dbValue");
var m = typeof(Enum).GetMethod("IsDefined", [typeof(Type), typeof(object)]);
//test
var testExp = Expression.Call(null, m, enumTypeExp, dbValueExp);
//true
var objExp = Expression.Convert(dbValueExp, typeof(object));
var strExp = Expression.Convert(objExp, typeof(string));
m = typeof(Enum).GetMethod("Parse", [typeof(Type), typeof(string)]);
var retExp = Expression.Call(null, m, enumTypeExp, strExp);
objExp = Expression.Convert(retExp, enumType);
//var returnExp = Expression.Return(labeleExp, objExp);
//false
//var x = Expression.Lambda(dbValueExp).CompileFast();
//var x = Expression.Lambda(dbValueExp).Compile();
var falseExp = Expression.Throw(Expression.Constant(new Exception($"could not convert \" {{how to get the input parameter value ??}} \" to type \"{typeof(TEnum).Name}\".")));
var xxExp = Expression.IfThenElse(testExp, objExp, falseExp);
//var block = Expression.Block(objExp, falseExp);
//return Expression.Lambda(block, dbValueExp).CompileFast();
return Expression.Lambda(xxExp, dbValueExp).Compile();
Подробнее здесь: [url]https://stackoverflow.com/questions/79202145/c-sharp-trying-to-convert-a-method-to-expression-tree-got-an-error-system-voi[/url]