简体   繁体   English

如何在VB.NET中进行C风格转换?

[英]How can I do C style casting in VB.NET?

I have a object type variable (control .Tag) that I need to cast to a structured type, and change a member in. This is a contrived but representative example: 我有一个对象类型变量(control .Tag),我需要将其转换为结构化类型,并更改成员。这是一个人为但有代表性的例子:

Public Structure struct_COLOURS
  Dim ILikeRed as boolean
  Dim ILikeGreen as boolean
End Structure

Dim AnObject as Object = (some source that is struct_COLOURS)

DirectCast(AnObject, struct_COLOURS).ILikeRed = True ' This is not valid syntax?!

I don't remember my C syntax very well, but it would be something like this: 我不太清楚我的C语法,但它会是这样的:

(struct_COLOURS*)AnObject->ILikeRed = true;

The point is I can cast an object to something and set members in the resulting cast. 关键是我可以将对象转换为某个对象并在结果转换中设置成员。 It seems as though DirectCast is actually a function and is not casting in the way I would interpret it. 似乎DirectCast实际上是一个函数,并没有按照我解释它的方式进行转换。

Oddly, if you only want to retrieve a member value, you can use DirectCast: 奇怪的是,如果您只想检索成员值,可以使用DirectCast:

dim YummyRed AS Boolean = DirectCast(AnObject, struct_COLOURS).ILikeRed

is just fine! 很好!

If I cannot cast the way I want, and I cannot change the use of the Tag property (so please don't suggest, it's not an option) to store these structures, what is the fastest way to set members? 如果我不能按照我想要的方式进行转换,并且我无法更改Tag属性的使用(所以请不要建议,这不是一个选项)来存储这些结构,设置成员的最快方法是什么?

It seems as though DirectCast is actually a function and is not casting in the way I would interpret it. 似乎DirectCast实际上是一个函数,并没有按照我解释它的方式进行转换。

No, that's wrong: DirectCast isn't a method, it's a real language construct, like a cast in C. 不,那是错的: DirectCast不是一种方法,它是一种真正的语言结构,就像C语言中的DirectCast一样。

However , if you store a structure (= value type) in an object, it gets boxed and, by consequence, copied . 但是 ,如果在对象中存储结构(=值类型),它将被装箱 ,并因此被复制 This is causing the problem here: you're attempting to modify a copy, not the original, boxed object. 这导致了这里的问题:您正在尝试修改副本,而不是原始的盒装对象。

So in order to change a member of a boxed value type object, you need to copy the object, change its value, and copy it back: 因此,为了更改盒装值类型对象的成员,您需要复制对象,更改其值并将其复制回来:

Dim tmp = DirectCast(AnObject, struct_COLOURS)
tmp.ILikeRed = True
AnObject = tmp

Incidentally, the same is true in C#, despite the superficial similarity to the C cast syntax. 顺便提一下,尽管与C cast语法表面相似,但在C#中也是如此。

That's how you should cast - with CType: 这就是你应该如何施展 - 使用CType:

Dim myColor As Object = Nothing
        Dim color As Color = CType(myColor, Color)
        color.Name = "red"

Why a struct and not a class? 为什么一个结构而不是一个类?

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

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