有没有办法将这些几乎相同的类合并为一个?

这个问题的后续问题: 为什么Nullable 被认为是结构而不是类?

我有两个类,基本上维护一个用户提供的值的元组与内部对象。

当用户提供的值的类型是基元时,我必须将它包装在Nullable以便它可以在元组中采用空值。

 public class BundledClass where T : class { private Tuple _bundle; public T Value { get { return _bundle == null ? null : _bundle.Item1; } set { _bundle = new Tuple(value, internalObj); } } //... public class BundledPrimitive where T : struct { private Tuple _bundle; public T? Value { get { return _bundle == null ? null : _bundle.Item1; } set { _bundle = new Tuple(value, internalObj); } } //... 

如果我能用一个可以将基元或类作为类型参数的类来做这个,我更喜欢它,但我没有看到任何解决方法。 并非没有提出某种自定义Nullable类,它可以包装任何类型(不仅仅是where T:struct类型),以确保始终可以为Value赋值;

似乎我至少应该能够将后一类定义为

 public class BundledPrimitive : BundledClass { } 

但即便失败,因为Nullable不符合: class约束(根据链接的问题)。

如果你只是像这样设计你的类:

 public abstract class Bundled { private Tuple _bundle; public T Value { get { return _bundle == null ? default(T) : _bundle.Item1; } set { _bundle = new Tuple(value, internalObj); } } } 

然后,您可以通过将type参数指定为Nullable将其与结构一起使用,例如:

 Bundled foo; // handles classes Bundled bar; // handles structs 

这里唯一的问题是用户可能将此类与非可空结构一起使用 – 例如Bundled 。 如果您的应用程序确实存在问题,您可以声明更具体的子类型,如下所示:

 public class BundledClass : Bundled where T : class { } public class BundledStruct : Bundled where T : struct { } 

您还可以为Bundled内部构造函数,以便无法从程序集外部调用它。 这将确保用户不创建自定义子类型以绕过BundledClass / BundledStruct包装器。

我能想到的最好的。 它仍然是两个类,但它使我免于数百行代码重复:

 public abstract class Bundled { protected Tuple _bundle; public abstract T Value { get; set; } //... Everything else } public class BundledClass : Bundled where T : class { public sealed override T Value { get { return _bundle == null ? null : _bundle.Item1; } set { _bundle = new Tuple(value, internalObj); } } } public class BundledPrimitive : Bundled where T : struct { public sealed override T? Value { get { return _bundle == null ? null : _bundle.Item1; } set { _bundle = new Tuple(value, internalObj); } } }