将列表传递给另一个班级 [英] Passing a List to another class

查看:65
本文介绍了将列表传递给另一个班级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这里的一些代码不清楚.我仍在尝试事物.我有三个问题,为什么在列表中添加字符串时会出现错误?如何将Class1中的List传递给我的主班?我的语法在列表passArr中正确吗?不知道是否应该在passArr的末尾添加括号.

I know some codes here are not clear. I'm still in the process of trying out things. I've got three questions, why does an error shows up when adding a string in my list? How do I pass the List in Class1 to my main class? And is my syntax correct in List passArr? Not sure if I should add parenthesis at the end of passArr.

class Class1
{
    public static List<string> passArr
    {
        get;
        set;
    }

    public static void passIt()
    {
        passArr.Add("A"); //Error: Object reference not set to an instance of an object
    }
}

主类

class Program
{
    static void Main(string[] args)
    {
        Class1.passIt();
        List<string> passArr1 = Class1.passArr;
        foreach (string s in passArr1)
        {
            Console.WriteLine(s);
        }
        Console.ReadLine();
    }
}

推荐答案

您永远不会创建列表,因此passArr属性(需要重命名)总是有一个null的值.您需要类似的东西:

You're never creating a list, so the passArr property (which needs renaming, by the way) always has a value of null. You need something like:

Class1.passArr = new List<string>();

在某个时候.另一种选择是使它成为由带有初始化程序的字段支持的只读属性:

at some point. Another alternative would be to make it a read-only property backed by a field with an initializer:

private static readonly List<string> passArr = new List<string>();
public static List<string> PassArr { get { return passArr; } }

(这符合 case 的命名约定,但是,它仍然不是一个有意义的名称.)

(This complies with naming convention in terms of case, but it's still not a meaningful name, of course.)

这篇关于将列表传递给另一个班级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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