C# 列表用途不在Main()中-
该功能运行良好 如果将动态值添加到其他类中,我仍然希望在Main中声明list0。怎么做 多谢各位C# 列表用途不在Main()中-,c#,class,list,C#,Class,List,该功能运行良好 如果将动态值添加到其他类中,我仍然希望在Main中声明list0。怎么做 多谢各位 using System; using System.Collections.Generic; using System.Text; class Program { public static void Main() { List<string> list0 = new List<string>(); list0.Ad
using System;
using System.Collections.Generic;
using System.Text;
class Program
{
public static void Main()
{
List<string> list0 = new List<string>();
list0.Add("A"); // Move to other class.
list0.Add("B"); // Move to other class.
string line0 = string.Join("/", list0.ToArray());
Console.WriteLine(line0);
Console.ReadLine();
}
}
======================================
更新
在你的帮助下。我的问题解决了。下面还有一个问题
using System;
using System.Collections.Generic;
using System.Text;
public class Program
{
public static void Main()
{
List<string> list0 = new List<string>();
list0.Add("A");
list0.Add("B");
otherClass oAdd = new otherClass();
oAdd.AddItem(list0);
string line0 = string.Join("/", list0.ToArray());
Console.WriteLine(line0);
Console.ReadLine();
}
}
public class otherClass
{
//error CS0117: 'otherClass' does not contain a definition for 'AddItem'
// If uncommented and switch to this line show the error above. I don't know why?
//public static void AddItems(IList<string> list0)
public void AddItem(IList<string> list0)
{
list0.Add("C");
list0.Add("D");
}
}
我发现了另一个问题。谢谢
public class OtherClass
{
public OtherClass(IList<string> list0)
{
list0.Add("A");
list0.Add("B");
}
}
或
这是因为列表是引用类型,所以您要传递引用,然后将项添加到位于该引用处堆上的列表类中。能否请您更具体一些?你到底想干什么?你想让Add操作位于一个单独的方法中,该方法将列表作为参数接收?将列表设为属性,然后尝试从其他类设置它?@Moshe,是的,正如你所说。我希望Add操作位于单独的Classmethod中,然后将列表作为参数接收。谢谢。要使用static,您不需要声明类的实例。你只需要使用otherClass.AddItemlist0.Hi Yuriy,我遵循了你的指导。我发现只有一种方法有效。你能检查一下我上面的代码吗。谢谢。@Nano他查看我对你的问题的评论。
public class OtherClass
{
public static void AddItems(IList<string> list0)
{
list0.Add("A");
list0.Add("B");
}
}