如何比较不同类型的物体

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

寻找一种方法来查找两个对象之间的对象。尝试使用

将整数转换为小数
static bool Between(object value, object low, object high)
  {
    if (value == null && low == null && high == null)
      return false;

    if (value is int || low is int || high is int ||
      value is decimal || low is decimal || high is decimal ||
      value is double || low is double || high is double ||
      value is int? || low is int? || high is int? ||
      value is decimal? || low is decimal? || high is decimal? ||
      value is double? || low is double? || high is double? )
     return (decimal)(value ?? 0) >= (decimal)(low ?? 0) && (decimal)(value ?? 0) <= (decimal)(high ?? 0);

    if (value is DateOnly || low is DateOnly || high is DateOnly ||
      value is DateOnly? || low is DateOnly? || high is DateOnly?)
      return (DateOnly)(value ?? DateOnly.MinValue) >= (DateOnly)(low ?? DateOnly.MinValue) && (DateOnly)(value ?? 0) <= (DateOnly)(high ?? DateOnly.MinValue);

    if (value is string || low is string || high is string ||
      value is char || low is char || high is char
      value is string || low is string || high is string ||
      value is char? || low is char? || high is char? )
    {
      string av = (string)(value ?? "");
      string slow = (string)(low ?? "");
      string shigh = (string)(high ?? "");
      return av.CompareTo(slow) >= 0 && av.CompareTo(shigh) <= 0;
    }
    throw new ArgumentException("Incompatible argument types");
  }

使用混合整数和小数参数

 Between((int)1 , (decimal)1, (decimal) 2 )

抛出异常

无法将整数转换为小数

如何修复此方法,使其在参数为 int、decimal、double、int?、decimal 时有效?还是双? 任意组合。 使用对象类型的动态参数类型可以让事情变得更容易吗?

使用 ASP .NET 8 MVC 和最新的 C#

c# asp.net casting compare
1个回答
0
投票

作为快速解决方案,您可以使用decimal.TryParse() 和 ToString()。

    object input1 = (int)1;
    object input2 = (int)2;
    decimal.TryParse(input1.ToString(), out decimal parse);
    bool compareBool1 = (decimal)parse <= (decimal)input2; // This works.
    bool compareBool2 = (decimal)input1 <= (decimal)input2; // InvalidCastException

但是,仍然存在很多问题。

© www.soinside.com 2019 - 2024. All rights reserved.