你能在结构中有一个类吗? [英] Can you have a class in a struct?

查看:32
本文介绍了你能在结构中有一个类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C# 中是否有可能有一个带有类类型成员变量的结构?如果是这样,信息存储在何处,在堆栈、堆或两者中?

Is it possible in C# to have a Struct with a member variable which is a Class type? If so, where does the information get stored, on the Stack, the Heap, or both?

推荐答案

是的,你可以.指向类成员变量的指针与结构体的其余值一起存储在栈上,而类实例的数据存储在堆上.

Yes, you can. The pointer to the class member variable is stored on the stack with the rest of the struct's values, and the class instance's data is stored on the heap.

结构也可以包含类定义作为成员(内部类).

Structs can also contain class definitions as members (inner classes).

这里有一些非常无用的代码,至少可以编译并运行以表明这是可能的:

Here's some really useless code that at least compiles and runs to show that it's possible:

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;
            }
        }
    }
}

这篇关于你能在结构中有一个类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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