我有一个类,我用它来指定如下类型
public class TypeSpec
{
// String specifications
public int? maxLength {get; set;} = null;
public int? minLength {get; set;} = null;
// int specifications
public int? maxInteger {get; set;} = null;
public int? minInteger {get; set;} = null;
}
TypeSpec typeInitialString = new TypeSpec()
{
maxLength = 10;
minLength = 0;
}
TypeSpec typeUpdatedString = new TypeSpec()
{
maxLength = 10;
minLength = 5;
maxInteger = 0;
}如何检查TypeSecond是否仍然使用MaxInteger作为null,并触发false,以确保此处更改的值仅为maxLength和MinLengthfrom 0-10到5-10?
我想用typeUpdatedString修改我用typeInitialString设置的初始类型标准。但在这样做之前,我需要验证规范是否不包含其他类型的规范,如整数?因为typeInitialString仅用于字符串,而不用于其他
做普通的相等将失败,因为值可以不同,我想避免成员变量,以前是null仍然是空的更新版本。
发布于 2020-03-01 20:26:43
在这个问题上也不是完全清楚。在typeB.maxInteger为null时返回false的简单版本如下所示:var result = typeB.maxInteger.HasValue ? true : false;
尽管您似乎正在尝试实现一些自定义的对象相等性检查,因此您需要了解一下如何实现IEquatable和相关的重载:
public class TypeSpec : IEquatable<TypeSpec>
{
public int? maxLength { get; set; } = null;
public int? minLength { get; set; } = null;
public int? maxInteger { get; set; } = null;
public int? minInteger { get; set; } = null;
public static bool operator ==(TypeSpec a, TypeSpec b)
=> a.Equals(b);
public static bool operator !=(TypeSpec a, TypeSpec b)
=> !a.Equals(b);
public bool Equals(TypeSpec other)
{
var result = GetHashCode() == other.GetHashCode();
return result;
}
public override bool Equals(object obj)
{
return this == obj as TypeSpec;
}
public override int GetHashCode()
{
var maxI = maxInteger.HasValue ? maxInteger.Value : default;
var minI = minInteger.HasValue ? minInteger.Value : default;
var minL = minLength.HasValue ? minLength.Value : default;
var maxL = maxLength.HasValue ? maxLength.Value : default;
var result = (maxI + minI + minL + maxL).GetHashCode();
return result;
}
}
public class Program
{
public static void Main()
{
TypeSpec typeA = new TypeSpec()
{
maxLength = 10,
minLength = 0
};
TypeSpec typeB = new TypeSpec()
{
maxLength = 10,
minLength = 0,
maxInteger = null
};
var result = typeB == typeA;
}
}发布于 2020-03-01 20:45:00
我猜您想要比较typeA和typeB的属性值。有几种方法。最简单的是比较每个属性。如果typeA.MaxInt为null且typeB.MaxInt为null,则typeA.MaxInt == typeB.MaxInt将返回true。
https://stackoverflow.com/questions/60474903
复制相似问题