抱歉,这是一个基本问题,我找不到答案。
我必须用 C# 编写一些代码,并且我需要创建一个作为引用的类成员变量。
在 C++ 中,这段代码将是
public class MyClass
{
MyClass(int& m_var): mVar(m_var){}
int& mVar;
}
但是我似乎无法在 C# 中执行此操作
我可以使用引用参数创建一个构造函数
MyClass(ref int m_var)
但是我不能使用
创建引用成员变量
class MyClass
{
MyClass(ref int m_var)
{
mVar = m_var;
}
ref int mVar;
}
因为行:
ref int mVar;
给我错误:'Invalid Token 'ref' in class, struct, or interface member declaration.
这是为什么?为什么 C# 取消了创建引用成员变量的功能?
int is just a placeholder for another class here
哇哦! int
不仅仅是“另一类”。 int
是一个值类型。你不能有一个引用它的字段。你可以有一个ref
范围。在 C#7 中你可以有 ref
返回和本地人,但仍然不是领域。
在 CLR 中,int
与我们在这里讨论的领域中的类(class)截然不同。 x
是我们形象地称为“堆栈”的整数,因为我不想查看他们实际是如何实现它的。在 C 中,我似乎记得将其描述为堆栈变量:
int x = 0;
List<T>
是一个类。 y
,在这里,是一个“堆栈变量”,它是对“堆”上对象的可重新绑定(bind)引用:
var y = new List<int>();
如果您正在谈论共享对引用类型的引用——任何 class
-- 在 C# 中很简单:它始终是一个引用。
public class C {
// x is passed by value. It is the value of a reference. Seriously, it is.
public C(List<String> x) {
List = x;
}
public List<String> List { get; set; }
}
...
var list = new List<String>();
var x = new C(list);
var y = new C(list);
x.List
和 y.List
是同一个对象,至少在您将新对象分配给其中一个对象之前是这样——C# 引用与 C++ 引用(至少从 C++98 开始;我自 2006 年以来就没有跟上)是“可重新绑定(bind)”的。
做到这一点的方法是编写一个带有 int
的简单类属性,并共享对该实例的引用。 where T : struct
限制 T
成为struct
而不是一个类。在 CLR 领域,这意味着“值类型”而不是“引用类型”。
public class Reference<T> where T : struct
{
public Reference(T t) {
Value = t;
}
public T Value { get; set; }
}
class MyClass
{
MyClass(Reference<int> ref)
{
_ref = ref;
}
Reference<int> _ref;
}
Why did C# take away the functionality to create reference member variables?
他们没有“把它拿走”;他们没有绑架婴儿 C++ 编译器并切断它的脚趾。他们只是认为在 C# 中这样做不是一个好主意,他们是对的。 C# 不是 C,也不意味着是 C。Dennis Ritchie 设计 C 是为了让像 Ken Thompson 这样的人使用; Anders Hejlsberg 明确设计了 C# 供我们其他人使用,这些人更容易混淆。
This is built deeply into .NET :
The CLR type system however does not allow for fields that are aliases to other variables
(那是一篇旧文章;C#7 现在确实支持 CLR 一直支持的 ref
的其他用途)。
新的 C# 程序员已经对 ref
产生了足够多的麻烦。和引用类型。就在最近,我在这里看到一个问题中的代码很像这样:
public void F(ref List<int> x) { ... }
写那段代码的人只是想传入一个 List<int>
无需创建昂贵的副本。