C#参考成员变量 [英] C# reference member variable

查看:84
本文介绍了C#参考成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,有没有一种方法可以将引用保留为对象中的成员变量(如C ++中的对象指针),而不仅仅是保留为参数?

我如何才能使指针或对象引用作为成员变量?

How can I make a pointer or reference to an object as a member variable?

推荐答案

如果您的意思是 ref参数传递约定,那么不能,您不能存储它.从MSDN上的第一个注释起:

If you mean ref the argument passing convention, then no, you cannot store this. From the first note on MSDN:

不要混淆按引用传递的概念与引用类型的概念.这两个概念不一样...

Do not confuse the concept of passing by reference with the concept of reference types. The two concepts are not the same...


编辑:根据您更新的问题,C#在指针和引用方面有不同的命名法. C#中的指针不安全有点的em>构造直接引用对象的内存位置.我之所以这么说是因为内存位置可以根据垃圾回收而改变(除非您将其修复在内存中).


Edit: based on your updated question, C# has different nomenclature about pointers and references. A pointer in C# is an unsafe construct used to somewhat directly reference the memory location of an object. I say somewhat because the memory location can change based on garbage collection (unless you fix it in memory).

引用是默认的引用类型传递并存储.它们类似于其他语言中的 pointers (指针),但并不完全相同.但是,通过 by-reference 参数传递约定,您可以直接更改对象所指的内容.

References in C# are the default way reference types are passed and stored. They are akin to pointers in other languages, but not quite the same. However, the by-reference argument passing convention allows you to directly change what an object refers to.

如果您的目标是对非引用类型的局部变量保留可变引用,则必须将局部变量封装在

If your objective is to keep a mutable reference to a non-reference type local variable, you'll have to encapsulate the local variable in a reference type (like a class). If you could give some sample code, we can give some specific examples.

这篇关于C#参考成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆