我已经在代码中犯了两次相同的错误,如下所示:
void Foo(Guid appId, Guid accountId, Guid paymentId, Guid whateverId)
{
...
}
Guid appId = ....;
Guid accountId = ...;
Guid paymentId = ...;
Guid whateverId =....;
//BUG - parameters are swapped - but compiler compiles it
Foo(appId, paymentId, accountId, whateverId);
好的,我想防止这些错误,所以我创建了强类型 GUID:
[ImmutableObject(true)]
public struct AppId
{
private readonly Guid _value;
public AppId(string value)
{
var val = Guid.Parse(value);
CheckValue(val);
_value = val;
}
public AppId(Guid value)
{
CheckValue(value);
_value = value;
}
private static void CheckValue(Guid value)
{
if(value == Guid.Empty)
throw new ArgumentException("Guid value cannot be empty", nameof(value));
}
public override string ToString()
{
return _value.ToString();
}
}
另一个用于 PaymentId:
[ImmutableObject(true)]
public struct PaymentId
{
private readonly Guid _value;
public PaymentId(string value)
{
var val = Guid.Parse(value);
CheckValue(val);
_value = val;
}
public PaymentId(Guid value)
{
CheckValue(value);
_value = value;
}
private static void CheckValue(Guid value)
{
if(value == Guid.Empty)
throw new ArgumentException("Guid value cannot be empty", nameof(value));
}
public override string ToString()
{
return _value.ToString();
}
}
这些结构几乎相同,有很多重复的代码。不是吗?
除了使用类而不是结构之外,我想不出任何优雅的方法来解决它。我宁愿使用结构,因为空检查,更少的内存占用,没有垃圾收集器开销等......
您知道如何在不重复代码的情况下使用 struct 吗?
慕雪6442864
LEATH
12345678_0001
相关分类