C# 反射将字段对象从字段名称转换为 C# 代码? [重复]

问题描述 投票:0回答:1

我有一个编码问题,认为反射可能是满足 C# VS-2022 源代码情况的方法。

我的问题是阅读完以下内容后...反射可用于简化用于订购列表的硬编码

field-name
吗?

我有这句话,其中

r.TXT_DISPL_VEHICLE
代码显然已输入到源代码中。

case 1:
// For the first sort-box, ALWAYS sort by the 'DTTM_TRIP_START_DATE'.
_ListForGrid = _ListForGrid.AsQueryable().OrderBy(r => r.DTTM_TRIP_START_DATE)
               .ThenByDescending(r => r.TXT_DISPL_VEHICLE).ToList();

但是,该字段名称

TXT_DISPL_VEHICLE
基于用于排序语句的类名称。 我们有很多项目调用这个函数,例如:

class-name          field-name
----------------    --------------------
"Vehicle"       ,   "TXT_DISPL_VEHICLE"         
"Department"    ,   "TXT_DEPT_ABBREV"               
"Driver"        ,   "TXT_DISPL_DRIVER_NAME"     
"Manager"       ,   "TXT_DISPL_DRIVER_NAME" 

我想知道反射是否可以解决避免一系列 switch 语句的编码问题,例如:

switch (itemType) {
case "Vehicle":
//use the value TXT_DISPL_VEHICLE in the code for vehicle.
break;

...每个项目都类似。

此外,“排序”句子变得更加复杂,并且基于

OrderBy
子句中使用的项目数量...例如第三种排序类型...

case 3:
// For the first sort-box, ALWAYS sort by the 'DTTM_TRIP_START_DATE'.
if (saOrderBys[0] == "DESC") {
    int soValue13 = Convert.ToInt32(ddlOrderByFieldNamesList.FirstOrDefault(r => r.Key == iaSortDDLs[0]).Value);
    _ListForGrid = _ListForGrid.AsQueryable().OrderByDescending(r => r.DTTM_TRIP_START_DATE)
        .ThenBy(r => r.TXT_DISPL_VEHICLE)
        .ThenBy(r => r.TXT_DISPL_DRIVER_NAME).ToList();
} else if (iDESC == 2) {
    _ListForGrid = _ListForGrid.AsQueryable().OrderBy(r => r.DTTM_TRIP_START_DATE)
        .ThenByDescending(r => r.TXT_DISPL_VEHICLE)
        .ThenBy(r => r.TXT_DISPL_DRIVER_NAME).ToList();
} else if (iDESC == 3) {
    _ListForGrid = _ListForGrid.AsQueryable().OrderBy(r => r.DTTM_TRIP_START_DATE)
        .ThenBy(r => r.DTTM_TRIP_START_DATE)
        .ThenByDescending(r => r.TXT_DISPL_DRIVER_NAME).ToList();
}
return;
c# visual-studio reflection blazor-server-side
1个回答
0
投票

我建议使用新的

switch
表达式,这会简化语法:

// For the first sort-box, ALWAYS sort by the 'DTTM_TRIP_START_DATE'.
_ListForGrid = _ListForGrid
    .AsQueryable()
    .OrderBy(r => r.DTTM_TRIP_START_DATE)
    .ThenByDescending(r => itemType switch
    {
        "Vehicle" => r.TXT_DISPL_VEHICLE,
        "Department" => r.TXT_DEPT_ABBREV,
        "Driver" => r.TXT_DISPL_DRIVER_NAME,
        "Manager" => r.TXT_DISPL_DRIVER_NAME,
    })
    .ThenBy(r => r.TXT_DISPL_DRIVER_NAME)
    .ToList();
© www.soinside.com 2019 - 2024. All rights reserved.