【问题标题】:Model with property that can be an any value type具有可以是任何值类型的属性的模型
【发布时间】:2021-07-28 18:12:53
【问题描述】:

我有一个获取 FilterState 模型的控制器方法。
该模型包含一个过滤器模型列表,其中包含值属性,可以是任何值类型(int、字符串、日期时间等)。
我如何编写这个类并确定从前端传给我的属性类型?

[HttpGet]
public async Task<GridResultViewModel<ItemGridViewModel>> GetFiltered(int modelId, 
  [FromQuery] FilterState filterState)
{
   ...
}

public class FilterState
{
   public int Skip { get; set; }
   public int Take { get; set; }
   public IEnumerable<Filter> Filters { get; set; }
}

public class Filter
{
   public string Operator { get; set; }
   public string Field { get; set; }
   public ??? Value { get; set; } // this can be string, int, datetime etc.
}

如果我将 Value 属性设为对象或动态类型,则始终为 null。
我在前端使用 Angular 11。

【问题讨论】:

  • 我认为这里唯一的选择是将类型设置为string,然后,可能基于另一个属性,尝试解析为特定类型

标签: c# .net angular api generics


【解决方案1】:
        public string Value { get; set; } = "str12";

        object CheckType(string value)
        {
            return
                int.TryParse(value, out int intVal) ? intVal :
                DateTime.TryParse(value, out DateTime datetimeVal) ? datetimeVal :
                value;
        }

        var result = CheckType(Value);
        if (result is int)
        {
            
        }
        if (result is string)
        {

        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-06
    • 1970-01-01
    • 2012-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-28
    • 2015-04-12
    相关资源
    最近更新 更多