有没有什么办法将这些几乎相同的类合并成一个? [英] Is there any way to combine these almost identical classes into one?
问题描述
跟进这个问题:为何为空< T>考虑一个结构,而不是一类?
我有两个班,基本上保持与内部对象某些用户提供的值的元组。
I have two classes that essentially maintain a tuple of some user-supplied value with an internal object.
当用户提供的值的类型是基本,我不得不把它包在可空< T>
等等。它可以在元组的空值
When the type of the user-supplied value is a primitive, I have to wrap it in a Nullable<T>
so that it can take on a null value in the Tuple.
public class BundledClass<T> where T : class
{
private Tuple<T, object> _bundle;
public T Value
{
get { return _bundle == null ? null : _bundle.Item1; }
set { _bundle = new Tuple<T, object>(value, internalObj); }
}
//...
public class BundledPrimitive<T> where T : struct
{
private Tuple<T?, object> _bundle;
public T? Value
{
get { return _bundle == null ? null : _bundle.Item1; }
set { _bundle = new Tuple<T?, object>(value, internalObj); }
}
//...
我更喜欢它,如果我可以,可以采取两种原始类型或者类作为一个类型参数一个类做到这一点,但我没有看到周围没有任何办法。不是没有想出某种自定义的可空
类,可以框的类型(而不仅仅是类型其中T:结构
),以确保值
总是可以被赋值为null;
I'd prefer it if I could do this with a single class that can take either primitives or classes as a type parameter, but I don't see any way around it. Not without coming up with some sort of custom Nullable
class that can box any type (not just types where T:struct
) so as to ensure that Value
can always be assigned null;
好像我应该至少能够定义后者类
It seems like I should at least be able to define the latter class as
public class BundledPrimitive<T> : BundledClass<T?> { }
但即使这样,因为失败可空< T>
不符合:类
约束(按照链接的问题)
But even that fails since Nullable<T>
does not meet the : class
constraint (as per the linked question).
推荐答案
如果你只是设计你的类是这样的:
If you simply designed your class like this:
public abstract class Bundled<T>
{
private Tuple<T, object> _bundle;
public T Value
{
get { return _bundle == null ? default(T) : _bundle.Item1; }
set { _bundle = new Tuple<T, object>(value, internalObj); }
}
}
然后就可以用一个结构指定使用它类型参数为可空< T>
,例如:
Bundled<string> foo; // handles classes
Bundled<float?> bar; // handles structs
这里唯一的问题是,它可能是一个用户可以使用这个类有非空的结构&MDASH;例如: 捆绑< INT>
。如果这是真的在你的应用程序一个问题,你可以声明更具体的子类型是这样的:
The only problem here is that it's possible that a user could use this class with a non-nullable struct—e.g. Bundled<int>
. If that's really a concern in your application, you could declare more specific sub-types like this:
public class BundledClass<T> : Bundled<T> where T : class { }
public class BundledStruct<T> : Bundled<T?> where T : struct { }
您也可以为捆绑<构造函数; T>
的内部,因此无法从您的程序集以外的调用。这将确保用户不会创建一个自定义子类型绕过你的 BundledClass
/ BundledStruct
包装。
You also can make the constructor for Bundled<T>
internal so it can't be called from outside your assembly. This will ensure that the user doesn't create a custom sub-type to bypass your BundledClass
/ BundledStruct
wrappers.
这篇关于有没有什么办法将这些几乎相同的类合并成一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!