如何访问对象中的对象? [英] How do I access an object in an object?

查看:89
本文介绍了如何访问对象中的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试将SubIdName.Id设置为某个值时,我得到了无效的初始化成员decapitator(我尝试了几种不同的方法)。我有一个具有子类的类,我需要在类和子类中设置对象。我认为这很容易,但我在尝试让任何想法发挥作用时遇到问题?



我尝试过的事情:



I am getting Invalid initialize member decapitator when I try to set SubIdName.Id to a value (I have tried several different ways of doing it). I have a Class that has a sub class and I need to set the objects in the class and the subclass. I figured this would be easy but I am having problems trying to get this to work any ideas?

What I have tried:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    public class subClass
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    public class mainClass
    {
      public string MainId { get; set; }
      public string description { get; set; }
      public subClass SubIdName { get; set; }

    }
    class Program
    {
        static void Main(string[] args)
        {
            mainClass m = new mainClass()
            {
                MainId = "Main ID Goest Here",
                description = "Main description goes here",
                SubIdName.Id = 1
            };

        }
    }
}

推荐答案

根据您的示例代码,您没有实例化内部对象。添加以下行:



According to your sample code, you haven't instantiated the inner object. Add this line:

mainClass m = new mainClass()
{
    MainId = "Main ID Goest Here",
    description = "Main description goes here",
    // use this instead of your existing assignment
    SubIdName = new subClass() { Id = 1 };
};





BTW,无论代码的意图如何,你都应该努力使用有意义的变量和类名。 subClass是一个真正糟糕的类名。在你学习的过程中养成良好的习惯,当你开始真正得到报酬来做这项工作时,你会更容易继续这些做法。



BTW, you should always strive to use meaningful variable and class names, regardless of the intent of the code. "subClass" is a REALLY bad name for a class. Develop good habits while you're learning, and you'll be more apt to continue those practices when you start to actually get paid to do the work.


这篇关于如何访问对象中的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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