在 C# 中使用变量时 List.Add 方法的问题

本文关键字:Add List 方法 问题 变量 | 更新日期: 2023-09-27 18:34:07

我目前无法使用字符串变量作为项目添加到列表中。 当我稍后拉取列表时,它只是返回 null:

public class JobStatus
{
    public static string _JobURI;
    public static string currentStatus = "no job";
    public static void checkStatus()
    {
        ...
        //define job URI
        List<string> jobURIs = new List<string>();
        jobURIs.Add(_JobURI);

但是,当我插入如下所示的字符串值而不是变量时,它会将其正确添加到列表中:

//define job URI
List<string> jobURIs = new List<string>();
jobURIs.Add("new item name");

不确定我错过了什么。

在 C# 中使用变量时 List.Add 方法的问题

根据您发布的代码,您获得 null _JobsURI的原因是您在此处声明它:

public static string _JobURI;

但你永远不会给它赋值。 根据文档:"已声明但尚未分配值的字符串为 null

尝试为 _JobURI 分配一个值,然后将其添加到List<string>

public static string _JobURI = "Some string here.";
我想

通了,开始程序员的错误。 我在同一类中使用了Get Set方法,并声明了上面建议的变量:

public static string currentStatus = "no job";
        private static string joburi = "";
        public static string JobURI
        {
            get { return joburi; }
            set { joburi = value; }
        }

谢谢你的帮助。