【问题标题】:Obtaining a reference to the object a variable is a member of获取对变量所属对象的引用
【发布时间】:2018-03-09 19:28:11
【问题描述】:

我有一个客户类:

Public Class Customer
   Public Name As String
End Class

然后我将名称传递给子例程 foo:

Dim myCustomer as New Customer
myCustomer.Name = "Bill"
Foo(myCustomer.Name)

使用反射,Foo 有没有办法获得对 name 参数所属的 MyCustomer instance 的引用?

Public Sub Foo (name As String)
   'Any way to obtain a reference to the MyCustomer instance from
   'the name parameter alone?
End Sub

【问题讨论】:

  • 不,在那一点上,它是一个普通的旧字符串,可能来自任何地方。
  • 您可以简单地传递对象实例本身并将 foo 参数更改为 Object 但如果您要传递来自具有不同属性的不同类的字符串,则需要编写代码来找出哪个类正在通过等

标签: .net vb.net reflection


【解决方案1】:

没有。

想想这些对象在内存中的样子。简而言之,它看起来像这样:

| Address | Value                 |
|---------|-----------------------|
| 0x01    | "Bill"                |
| 0x02    | Customer(Name = 0x01) |

当您调用该方法时,您将地址传递给字符串。

Foo(myCustomer.Name)

...等价于...

String n = myCustomer.Name; // n is now 0x01

Foo(n);

Foo 中,你只能看到 0x01。它没有指向存储客户实例的 0x02 的链接。您基本上必须强制使用内存来查找对 0x01 的引用,这在 VB 这样的高级内存管理语言中是不可能的(或者至少是良好的做法)。

唯一的选择是引入一个采用 Customer 类型的新重载,并且可能为非客户特定位调用 Foo(String)

【讨论】:

  • 谢谢。我希望通过 .NET 工具箱中的所有其他技巧(例如 NameOf、ParameterInfo 等)有办法做到这一点。
猜你喜欢
  • 2016-01-08
  • 2012-03-04
  • 2018-04-15
  • 1970-01-01
  • 2019-07-08
  • 1970-01-01
  • 1970-01-01
  • 2013-10-08
  • 2022-08-23
相关资源
最近更新 更多