如何在c#中动态添加类实例

本文关键字:添加 实例 动态 | 更新日期: 2023-09-27 18:21:45

我会问的问题可能很傻。

例如:我有两个类似的课程

public class Login
{
    public String Username;
    public String Pwd;
    public address address1;
}    

地址.cs

public class address
{
    public String location;
    public string phonenumber;
}

我是否可以在运行时使用for循环,以address2和address3作为Address类的实例来增加Login类的成员。这能做到吗。。我有一个这样使用的api,而不是使用地址作为列表/数组。如果我感到困惑,请告诉我。。提前谢谢。

如何在c#中动态添加类实例

我是否可以在运行时使用for循环,以address2和address3作为Address类的实例来增加Login类的成员。

没有。如果您想要多个地址,则应将类更改为具有地址的集合,而不是单个字段。不能在执行时向对象添加字段。我建议使用List<Address>

此外,我强烈建议使用属性而不是公共字段,并遵循.NET命名约定。

具体如何公开集合取决于您,但我要么通过只读属性公开List<Address>,要么公开AddAddressRemoveAddress的方法。我还试图使Address本身是不可变的,使用构造函数来处理它的所有方面,例如

public sealed class Address
{
    private readonly string location;
    private readonly string phoneNumber;
    public string Location { get { return location; } }
    public string PhoneNumber { get { return phoneNumber; } }
    public Address(string location, string phoneNumer)
    {
        // TODO: Validate that it's a valid phone number? Possibly the same
        // for location? Almost certainly prevent either from being null...
        this.location = location;
        this.phoneNumber = phoneNumber;
    }
}

您应该创建一个address类的数组:

public class Login
{
    public String Username;
    public String Pwd;
    public address[] address;
} 

然后使用它们:

Login l = new Login();
l.address = new address[3];
l.address[0].location = ...
l.address[2].phonenumber = ...
l.address[1].location = ...
l.address[2].location = ...
...etc...

尝试使用字典,例如

class Something
{
   public string Username;
   public string Password;
   public Dictionary<string,address> Address;
   public Something(string username, string password)
   {
      this.Username = username;
      this.Password = password;
      this.Address = new Dictionary<string, address>();
   }
}

添加这样的新变量:

void example()
{
     var Something x = new Something("username", "password");
     x.Address.Add("Address1",new address());
     x.Address.Add("Address2",new address());
     x.Address.Add("Address3",new address());
     x.Address.Add("Address4",new address());
     //next address what you want
}

参考:将数组键设置为字符串而不是int?