简体   繁体   English

VB.NET指向值类型的指针

[英]VB.NET Pointer to value types

VB.NET 2010, .NET 4 VB.NET 2010,.NET 4

Hello all, 大家好,

I'm by no means a good programmer and I'm just trying to wrap my head around some of this stuff, so please forgive me if this is a dumb question. 我绝不是一个优秀的程序员,我只是想把我的头放在其中,因此,如果这是一个愚蠢的问题,请原谅我。

I want the following to produce a message box that says "2", not "5": 我希望以下内容产生一个消息框,显示“ 2”而不是“ 5”:

Public Class SomeClass
  Private SomeInt As Integer = 5
  Private SomeListOfInts As New List(Of Integer)

  Public Sub New()
    SomeListOfInts.Add(SomeInt)
    SomeListOfInts(0) = 2
    MsgBox(SomeInt.ToString)
  End Sub
End Class

This doesn't work. 这行不通。 The message box says "5". 消息框显示“ 5”。 I think that I understand why to some degree. 我认为我在某种程度上理解了原因。 Since SomeInt is a value type, adding it to SomeListOfInts just adds a copy. 由于SomeInt是值类型,因此将其添加到SomeListOfInts只会添加一个副本。 I'm sorry if this is incoherent. 很抱歉,如果这是不一致的。 Is there any straightforward way to accomplish this? 有没有简单的方法可以做到这一点?

Thanks in advance, Brian 预先感谢,Brian

Edit: I just wanted to add, I suspect folks'll say "Why try to do this?"/"This is not a good thing to try to do." 编辑:我只是想补充一下,我怀疑人们会说“为什么要这样做?” /“这不是一件好事。” etc. I'm alright with that and would like to know a better approach if there is one, however, I am also generically curious about how something like this might be done, whether it's good practice or not. 等等,我很好,我想知道是否有更好的方法,但是,无论是否是好的实践,我都对如何完成这样的事情普遍感到好奇。 Also, if it isn't good practice (whatever that means), why? 另外,如果这不是一个好习惯(无论意味着什么),为什么呢?

It is output 5 because your MsgBox is referencing SomeInt , not SomeListOfInts(0) 输出为5,因为您的MsgBox引用的是SomeInt而不是 SomeListOfInts(0)

Try this: 尝试这个:

Public Class SomeClass
  Private SomeInt As Integer = 5
  Private SomeListOfInts As New List(Of Integer)

  Public Sub New()
    SomeListOfInts.Add(SomeInt)
    SomeListOfInts(0) = 2
    MsgBox(SomeListOfInts(0).ToString) // here is the change
  End Sub
End Class

This... 这个...

SomeListOfInts(0) = 2

changes indexed element 0 in your list from 5 (the original value of element 0) to 2. Also, int is a value type. 将列表中的索引元素0从5(元素0的原始值)更改为2。而且, int是值类型。 Therefore, when you add SomeInt to the list, you have created a copy of the value type. 因此,当您将SomeInt添加到列表中时,您已经创建了值类型的副本。 The copy can be changed without affecting the original SomeInt . 可以更改副本而不会影响原始的SomeInt

You could start with: 您可以从以下内容开始:

Private ListOfInts As New List(Of Integer) 私有ListOfInts作为新列表(整数)

Public Sub New(SomeInt As Integer)
    ListOfInts.Add(SomeInt)

    ' processes

    ListOfInts(0) = 2
    MsgBox(SomeListOfInts(0).ToString)
End Sub

Maybe with a little more background on exactly what you are trying to do, I can help you get closer to your expectations. 也许您对您正在尝试做的事情有了更多的了解,我可以帮助您更加接近您的期望。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM