我需要一些帮助,了解如何在Main方法中使用一些示例值初始化以下对象,以执行某些操作。
由于我是C#的新手,请指导我在哪里可以获取此信息。
class MobOwner
{
public string Name { get; set; }
public List<string> Mobiles { get; set; }
}
我需要一些帮助,了解如何在Main方法中使用一些示例值初始化以下对象,以执行某些操作。
由于我是C#的新手,请指导我在哪里可以获取此信息。
class MobOwner
{
public string Name { get; set; }
public List<string> Mobiles { get; set; }
}
class MobOwner
{
public string Name { get; set; }
public List<string> Mobiles { get; set; }
public MobOwner() {
this.Mobiles = new List<string>();
}
}
class MobOwner
{
public string Name { get; set; }
public List<string> Mobiles { get; set; }
public MobOwner(IEnumerable<string> values) {
this.Mobiles = values.ToList();
}
}
new MobOwner(new[] { "Mario", "Hans", "Bernd" })
Mobiles
属性中使用set;
:通常我们会添加/更新/删除列表中的项目,而不是整个分配列表。 MobOwner sample = new MobOwner(...);
sample.MobOwner.Add("123");
sample.MobOwner.Add("456");
sample.MobOwner.RemoveAt(1);
sample.MobOwner[0] = "789";
sample.MobOwner = null; // we, usually, don't want such code
class MobOwner {
public string Name { get; set; }
public List<string> Mobiles { get; } = new List<string>();
public MobOwner(string name, IEnumerable<string> mobiles): base() {
if (null == name)
throw new ArgumentNullException("name");
if (null == mobiles)
throw new ArgumentNullException("mobiles");
Name = name;
Mobiles.AddRange(mobiles);
}
}
var owner = new MobOwner();
owner.Mobiles = new List<string>{"first", "second"};
var owner = new MobOwner {Mobiles = new List<string> {"first", "second"}};
class MobOwner
{
public string Name { get; private set; }
public List<string> Mobiles { get; private set; }
// constructor
public MobOwner(string name, List<string> mobiles)
{
Name = name;
Mobiles = mobiles;
}
}
这将创建一个 MobOwner
对象,其中包含一个项目列表。
MobOwner item = new MobOwner()
{
Name = "foo",
Mobiles = new List<string>() { "bar" }
};
class MobOwner
{
public string Name { get; set; }
public List<string> Mobiles { get; set; }
public MobOwner(string Name, params string[] Mobiles)
{
this.Name = Name;
this.Mobiles = new List<string>(Mobiles);
}
}
用法:
MobOwner item2 = new MobOwner("foo", "bar", "bar");
var mobOwner = new MobOwner()
{
Name = "name";
Mobiles = new List<string>()
{
"mob1",
"mob2",
"mob3"
};
};
如果我理解你的意图正确,你想在“Main”方法中初始化这些值。
构造函数是一种很好的方式,可以在创建类的实例时使用默认值来初始化属性。 但是,如果你想在其他地方初始化它们,请创建类的实例,然后可以为其公共成员赋值。像这样:
MobOwner mobOwner = new MobOwner();
mobOwner.Name = "Jimmy";
mobOwner.Mobiles = new List<string>{119, 011};
或者更现代的方式是可以像这样改变语法(虽然它们是相同的):
MobOwner mobOwner = new(){
Name = "Jimmy",
Mobiles = new List<string>{119, 011}
};