你可以在一个结构的一类? [英] Can you have a class in a struct?

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

问题描述

是否有可能在C#中有一个成员变量是一个类类型的Struct?如果是这样,哪里的信息得到存储在堆栈,堆,或两者兼而有之?

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天全站免登陆