0

我要问的可能很愚蠢。

例如:我有两个课程,例如

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 的类 Login 的成员作为类 Address 的实例递增吗?这可以做到吗..我有一个这样使用的api,而不是使用地址作为列表/数组。如果我感到困惑,请告诉我..提前谢谢。

4

3 回答 3

2

我可以在运行时使用 for 循环将具有 address2 和 address3 的类 Login 的成员作为类 Address 的实例递增吗?

不可以。如果您想要多个地址,您应该将您的班级更改为拥有一地址而不是单个字段。您不能在执行时向对象添加字段。我建议使用List<Address>.

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

究竟如何公开集合取决于你,但我要么公开List<Address>via 只读属性,要么公开AddAddressand的方法RemoveAddress。我也会尝试使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;
    }
}
于 2013-07-10T13:19:36.243 回答
1

您应该创建一个类数组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...
于 2013-07-10T13:19:46.120 回答
0

尝试使用Dictionary,例如

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?

于 2013-07-10T13:42:13.980 回答