我正在创建伪 - 值类型类以避免别名问题,但是实现了Equals(object)
,Equals(Type)
,GetHashCode()
的覆盖,以及==
和!=
运算符一遍又一遍地让我考虑将它重构为抽象基类。
由于这些将是“值”类型,我希望派生类为sealed
。
如果派生类不是Exception
,我当前的实现会在abstract
基类构造函数中抛出sealed
:
namespace SomeNamespace
{
public abstract class ValueType
{
private bool DerivedTypeIsSealed =>
(GetType().Attributes & TypeAttributes.Sealed) != 0;
protected ValueType()
{
if (!DerivedTypeIsSealed)
{ throw new UnsealedDerivedTypeException(
$"All types deriving from {nameof(ValueType)} must be sealed"); }
}
protected abstract int GetHashCodeFunction();
public override int GetHashCode() => GetHashCodeFunction();
public override bool Equals(object other)
{
return other != null &&
GetHashCode() == other.GetHashCode();
}
public static bool operator ==(ValueType left, ValueType right)
{
return left is null && right is null ||
!(left is null) && left.Equals(right);
}
public static bool operator !=(ValueType left, ValueType right) =>
!(left == right);
}
}
......但这在游戏中似乎有点晚了。
有没有办法声明一个抽象基类,这样当我尝试声明一个派生类isn时,预编译器(缺少一个更好的单词)会抱怨红色波浪线 t sealed
?关于我如何限制T
仅class
中的AbstractClass<T> where T : class