0

是否有一个类与这个类完全相等?

Class X(Of T)
    Public value As T
End Class

请注意,既不Nullable(Of T)也不Tuple(Of T)等于此类,因为它们不允许您设置成员值。该类应具有以下属性:

  1. 当作为参数传递时,被调用方法所做的任何更改都应该影响发送的对象,即它不应该像对固有类型那样创建对象的副本。
  2. 应该允许value使用语法将成员设置为一个值x.value = <some value>,其中 x 是 X 的对象。
4

2 回答 2

1

不是一个决定性的答案,但我会试一试。

我个人以前没有见过这种类型的课程。甚至关于泛型的文档也显示了一个与您在示例中创建和使用的类类似的示例类:

.net 框架中的 msdn 泛型。

这是示例:

Public Class Generic(Of T)
    Public Field As T

End Class

....

Public Shared Sub Main()
    Dim g As New Generic(Of String)
    g.Field = "A string" 
    '...
    Console.WriteLine("Generic.Field           = ""{0}""", g.Field)
    Console.WriteLine("Generic.Field.GetType() = {0}", g.Field.GetType().FullName)
End Sub
于 2013-02-25T10:37:17.933 回答
1

我有时会创建这样一个类,几乎是逐字逐句的,尽管我将类Holder<T>和字段称为Value;这样的类有两个很好的用例:

  • 给定 的集合Holder<someValueType>,可以方便地对集合的内容进行就地修改。例如,给定一个List<Holder<Point>>,可以说MyList[3].Value.X += 5;

  • 如果T是一种允许原子操作的类型,Holder<T>即使该集合不是线程安全的,也可以对集合的内容执行线程安全的原子操作。例如,在我事先知道字典所需的所有键的情况下,我创建了一个Dictionary<String, Holder<Integer>>,然后可以使用多个线程Interlocked.Increment来计算每个字符串出现的次数。尽管Dictionary不是线程安全的,但该程序在没有锁定的情况下是线程安全的,因为Holder<Integer>存储在字典中的项目集永远不必更改。

If you want to use a built-in type, there is one that would work: a T[] with size one. The main disadvantage of that type is that there's nothing inherent in the type which guarantees that element zero will actually exist (i.e. that it won't be an empty array).

于 2013-02-25T17:44:17.837 回答