请考虑以下代码(我有意将 MyPoint编写为此示例的引用类型)
public class MyPoint
{
public int x;
public int y;
}
Run Code Online (Sandbox Code Playgroud)
它是普遍公认的(至少在C#中)当你通过引用传递时,该方法包含对被操作对象的引用,而当你通过值传递时,该方法复制被操纵的值,因此全局范围中的值是不受影响.
例:
void Replace<T>(T a, T b)
{
a = b;
}
int a = 1;
int b = 2;
Replace<int>(a, b);
// a and b remain unaffected in global scope since a and b are value types.
Run Code Online (Sandbox Code Playgroud)
这是我的问题; MyPoint
是引用类型,所以我希望在相同的操作Point
,以取代a
与b
在全球范围内.
例:
MyPoint a = new MyPoint { x = 1, y = 2 };
MyPoint b = new …
Run Code Online (Sandbox Code Playgroud) c# value-type reference-type pass-by-reference pass-by-value
我可以想象这个问题已被问过几千次了,但是我找不到答案的运气也不多,而且这更多是出于好奇而不是需要.
深入研究C#的具体细节,我想知道,因为对象存储在堆中,堆中存储的对象中的值类型是否也被放置在堆栈中?
当我写作
Nullable<Nullable<DateTime>> test = null;
我收到编译错误:
The type 'System.Datetime?' must be a non-nullable value type in order to use it as a paramreter 'T' in the generic type or method 'System.Nullable<T>'
但Nullable<T>
它是struct
如此,它应该是不可空的.
所以我试着创建这个struct
:
public struct Foo<T> where T : struct
{
private T value;
public Foo(T value)
{
this.value = value;
}
public static explicit operator Foo<T>(T? value)
{
return new Foo<T>(value.Value);
}
public static implicit operator T?(Foo<T> value)
{
return new Nullable<T>(value.value);
} …
Run Code Online (Sandbox Code Playgroud) Nullable值类型是否会生成垃圾?例如:结构不是在堆上创建的,而是在堆栈上创建的,因为它是一个值类型.但是当该结构可以为空时,它仍然是值类型并仍然在堆栈上创建吗?
我问这个问题是因为我需要一个不会产生垃圾的可以为空的结构.