优化Object的InNotIn方法。增加String的In和NotIn方法。

This commit is contained in:
Falcon 2025-02-08 14:07:06 +08:00
parent d527ec9411
commit d133bf934d
3 changed files with 43 additions and 6 deletions

View File

@ -178,17 +178,12 @@ namespace Falcon.SugarApi.Test
public string ItemA { get; set; } = "itema";
}
public class ObjWithComparable
public class ObjWithComparable:IComparable<ObjWithComparable>
{
public int val { get; set; }
public int CompareTo(ObjWithComparable? other) {
return this.val - other.val;
}
public override bool Equals(object? obj) {
var c = obj as ObjWithComparable;
return c == null ? false : c.val == this.val;
}
}
}

View File

@ -221,6 +221,18 @@ namespace Falcon.SugarApi
return values.Any(a => a == null);
}
foreach(var i in values) {
if(i is IComparable<T> ict) {
if(ict.CompareTo(obj) == 0) {
return true;
}
continue;
}
if(i is IComparable ic) {
if(ic.CompareTo(obj) == 0) {
return true;
}
continue;
}
if(obj.Equals(i)) {
return true;
}
@ -228,6 +240,14 @@ namespace Falcon.SugarApi
return false;
}
/// <summary>
/// 判断对象是否不在目标对象数组中。如果对象实现IComparable则使用IComparable比较对象否则使用Equals方法比较对象
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="obj">当前对象</param>
/// <param name="values">目标对象数组</param>
/// <returns>不在数组中返回True否则False</returns>
public static bool NotIn<T>(this T obj,params T[] values) => !obj.In(values);
}
/// <summary>

View File

@ -199,5 +199,27 @@ namespace Falcon.SugarApi
return str;
}
/// <summary>
/// 判断字符串是否属于某个集合范围
/// </summary>
/// <param name="str">当前字符串</param>
/// <param name="strings">字符串范围</param>
/// <returns>属于True否则False</returns>
public static bool In(this string str,params string[] strings) {
foreach(var s in strings) {
if(str == s) {
return true;
}
}
return false;
}
/// <summary>
/// 和In方法相反判断字符串是否不属于某个集合范围
/// </summary>
/// <param name="str">当前字符串</param>
/// <param name="strings">字符串范围</param>
/// <returns>属于True否则False</returns>
public static bool NotIn(this string str,params string[] strings) => !str.In(strings);
}
}