我们可以在结构中上课吗?
时间:2020-03-05 18:54:58 来源:igfitidea点击:
在Cto中是否可能有一个带有成员变量的Struct,而该成员变量是Class类型?如果是这样,将信息存储在堆栈,堆或者两者上的什么位置?
解决方案
回答
是的你可以。指向类成员变量的指针与结构的其余值一起存储在堆栈上,而类实例的数据则存储在堆上。
结构还可以包含类定义作为成员(内部类)。
这是一些真正无用的代码,至少可以编译并运行以表明它是可能的:
using System; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { MyStr m = new MyStr(); m.Foo(); MyStr.MyStrInner mi = new MyStr.MyStrInner(); mi.Bar(); Console.ReadLine(); } } public class Myclass { public int a; } struct MyStr { Myclass mc; public void Foo() { mc = new Myclass(); mc.a = 1; } public class MyStrInner { string x = "abc"; public string Bar() { return x; } } } }
回答
建议不要这样做:参见http://msdn.microsoft.com/zh-cn/library/ms229017(VS.85).aspx
Reference types are allocated on the heap, and memory management is handled by the garbage collector. Value types are allocated on the stack or inline and are deallocated when they go out of scope. In general, value types are cheaper to allocate and deallocate. However, if they are used in scenarios that require a significant amount of boxing and unboxing, they perform poorly as compared to reference types.