我有兩節課:
class JoinedMapVoucher
{
public string Code1 { get; set; }
public string Code2 { get; set; }
public string Code3 { get; set; }
public DL DL1 { get; set; }
public DL DL2 { get; set; }
public DL DL3 { get; set; }
public DL DL4 { get; set; }
}
class DL
{
public long DLTypeRef { get; set; }
}
在這里,我有一個字典,其中鍵是 DLTypeRef,值是不應為空的代碼,例如在此示例中,如果 DLTypeRef 為 5,則 Code1 屬性應具有值且不能為空。我想做的是從字典中動態獲取不應為空的代碼。然后我想從 JoinedMapVoucher 型別中獲取該代碼并檢查它是否為空。在下面的代碼中,我寫了我想從字典中獲取代碼的注釋,然后從 JoinedMapVoucher 引數中獲取該屬性,但它不起作用。
var dic = new Dictionary<long, string>();
dic.Add(5, "Code1");
dic.Add(-1, "NullCode");
var dicConst = Expression.Constant(dic);
var list = Expression.Constant(new List<long> { 1, 2, 3, 4, 5 });
var defaultDL = new DL { DLTypeRef = -1, Id = -1 };
var foos = new List<JoinedMapVoucher> {new JoinedMapVoucher { DL2 = new DL { DLTypeRef = 5, Id = 55 } } }.AsQueryable();
var containsMethod = typeof(List<long>).GetMethod(nameof(List<long>.Contains), new[] { typeof(long) });
var parameter = Expression.Parameter(typeof(JoinedMapVoucher), "JoinedMapVoucher");
for (var i = 1; i <= 4; i )
{
var dl = Expression.PropertyOrField(parameter, "DL" i.ToString());
var actualDL = Expression.Coalesce(dl, Expression.Constant(defaultDL));
var dlTypeRef = Expression.PropertyOrField(actualDL, "DLTypeRef");
var or1 = Expression.Or(Expression.Equal(dlTypeRef, Expression.Constant((long)-1)), Expression.Not(Expression.Call(list, containsMethod, dlTypeRef)));
var dicGetItemMethod = typeof(Dictionary<long, string>).GetMethod("get_Item", new[] { typeof(long) });
var getCode = Expression.Constant(Expression.Call(dicConst, dicGetItemMethod, dlTypeRef)); **//here this call should return code from dictionary which it can be Code5 or NullCode**
**var needCode=Expression.PropertyOrFeild(parameter,getCode) // then i want to get Code property from parameter dynamically**
var lambda = Expression.Lambda<Func<JoinedMapVoucher, bool>>(or1, new ParameterExpression[] { parameter });
Console.WriteLine(lambda.Body);
foos = foos.Where(lambda);
}
如何在需要代碼變數中動態獲取屬性?
uj5u.com熱心網友回復:
您需要構建一個 switch 陳述句,該陳述句將打開getCode值并回傳相應的屬性。沿著這條線的東西:
var getCode = Expression.Call(dicConst, dicGetItemMethod, dlTypeRef);
SwitchExpression switchExpr =
Expression.Switch(
getCode,
Expression.Constant("-1"), // default case when none is matched
new SwitchCase[]
{
Expression.SwitchCase( // switch case for "Code1" returned from dict
Expression.PropertyOrField(parameter, nameof(JoinedMapVoucher.Code1)),
Expression.Constant( nameof(JoinedMapVoucher.Code1))
),
Expression.SwitchCase( // switch case for "NullCode" returned from dict
Expression.PropertyOrField(parameter, nameof(JoinedMapVoucher.Code2)),
Expression.Constant("NullCode")
),
}
);
這應該代表在您的 lambda 中生成的內容:
var code = dictionary[dlTypeRef];
switch (code)
{
case "Code1":
return JoinedMapVoucher.Code1;
case NullCode:
return JoinedMapVoucher.Code2;
default:
return "-1";
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/428919.html
