使用属性将值从一个类传递到另一个类 [英] Passing value from one class to another using property
本文介绍了使用属性将值从一个类传递到另一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个列表,我想从一个班级传递到另一个班级.代码如下:
Class1{内部 Class1(){MyList = new List();}//将内容添加到列表中MyList.Add("123");MyList.Add("234");公共静态 IList我的列表 { 获取;放;}}2级{var getList = Class1.MyList;}
每次运行此命令时,我都会在 Class2 中为 getList 获取空值.我做错了什么?
将编译的更新代码:
Class1{内部 Class1(){MyList = new List();}静态无效 Main1(string[] args){Class1 c = new Class1();c.MyList.Add("123");}公共 IList我的列表 { 获取;放;}}命名空间测试{2级{static void Main(string[] args){Class1 c = new Class1();var a = c.MyList;}}}
解决方案
这段代码会做你想做的,你不需要在你的类中声明一个静态的 Main 函数,而是使用构造函数初始化实例.
>
class 程序{static void Main(string[] args){Class2 instanceOfClass2 = new Class2();}}类 Class1{公共 IList我的列表 { 获取;放;}内部 Class1(){MyList = new List();MyList.Add("123");}}类 Class2{公共类 2(){Class1 c = new Class1();var a = c.MyList;}}
I have a list i am trying to pass from one class to another. Here is the code:
Class1
{
internal Class1()
{
MyList = new List<string>();
}
//Add stuff to list
MyList.Add("123");
MyList.Add("234");
public static IList<string> MyList { get; set; }
}
Class2
{
var getList = Class1.MyList;
}
Every time i run this i am getting null value in Class2 for getList. What am i doing wrong?
Updated code which will compile:
Class1
{
internal Class1()
{
MyList = new List<string>();
}
static void Main1(string[] args)
{
Class1 c = new Class1();
c.MyList.Add("123");
}
public IList<string> MyList { get; set; }
}
namespace Test
{
Class2
{
static void Main(string[] args)
{
Class1 c = new Class1();
var a = c.MyList;
}
}
}
解决方案
This code will do what you want, you don't need to declare a static Main function in your classes, instead initialize the instances using the constructor.
class Program
{
static void Main(string[] args)
{
Class2 instanceOfClass2 = new Class2();
}
}
class Class1
{
public IList<string> MyList { get; set; }
internal Class1()
{
MyList = new List<string>();
MyList.Add("123");
}
}
class Class2
{
public Class2()
{
Class1 c = new Class1();
var a = c.MyList;
}
}
这篇关于使用属性将值从一个类传递到另一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文