列表对象创建和分配值 [英] List Object creation and assign values

查看:113
本文介绍了列表对象创建和分配值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个课程: person 地址电话。一个人可以有多个地址,每个地址都有电话号码。这里如何初始化和分配多个地址和电话号码的值。以下是我的班级模特。



  public   class  Person 
{
public string 姓名{获取; set ; }
public string dob { get ; set ; }
public 列表<地址>地址{ get ; set ; }
public Person()
{
this .address = new 列表<地址>();
}
}

public class 地址
{
public string street {获得; set ; }
public string city { get ; set ; }
public string pobox { get ; set ; }
public string postalcode { get ; set ; }
public 手机电话{ get ; set ; }
public 地址()
{
.phone = new Phone();
}
}

public class 电话
{
public string 移动{获得; set ; }
public string 固定电话{ get ; set ; }
}

解决方案

引用:

如何初始化和赋值多个地址和电话号码。

有几种方法可以初始化/分配给您选择的任何Collection数据结构来保存多个值。以下示例反映了我喜欢的工作方式:

  public   enum  PhoneType 
{
Other,
Home,Mobile
}

public 枚举 AddressType
{
其他,
主页,办公室,PO_Box
}

public class Person
{
public string 名称{ get ; set ; }

// 请参阅下面的构造函数说明
public DateTime? Dob { get ; set ; }

public 字典< PhoneType,List< int>>电话{获取; set ; }
public 字典< AddressType,List< Address>>地址{ get ; set ; }

public Person( string 名称,
// 使用可空的DateTime是一种解决方法
// 因为参数中的DateTime
// < span class =code-comment> list必须是编译时常量
DateTime?dob,

// 请注意此处使用可选参数
字典< PhoneType,List< int>> phones = null
字典< AddressType,列表<地址>>地址= null


{
姓名=姓名;
// 注意在这里使用null-coalsescing运算符
Dob = dob? ? DateTime.MinValue;
手机=手机? new 字典< PhoneType,List< int>>();
地址=地址?? new 字典< AddressType,List< Address>>();
}

public void AddPhone(PhoneType ptype, int number)
{
// 要求Linq

如果(电话== null )电话= new 字典< PhoneType,List< int>>();

// 新型电话?使用新列表初始化< int>
如果(!Phones.ContainsKey(ptype))Phones.Add(ptype, new List< int>());

// 注意:此处不检查重复项:实施检查?
电话[ptype]。添加(数字);
}

public void AddPhones(PhoneType ptype,List< int>手机)
{
如果(电话== null )电话= new 字典< PhoneType,List< int>>();

// 新型电话?使用新列表初始化< int>
如果(!Phones.ContainsKey(ptype))Phones.Add(ptype, new List< int>());

电话[ptype] .AddRange(电话);
}

public void RemovePhone(PhoneType ptype, int number)
{
// 需要Linq

var numbersbykey = Phones.FirstOrDefault(kvp = > kvp.Key == ptype);

if (numbersbykey.Value!= null && numbersbykey。 Value.Contains(number))numbersbykey.Value.Remove(number);
}

// public void AddAddress(AddressType atype,string street,string city,string postalCode)
// {
// //您为此编写代码
// }

// public void RemoveAddress(AddressType atype,???)
// {
// //您为此编写代码
// }
}

注意:



1.我喜欢使用Enums,因为它们都有助于记录代码并且很容易扩展/ /将来改变



2.我喜欢使用带有枚举值的词典作为键,当每个键存储多个值时



3.我喜欢编写显式的Add方法,用于向集合中添加一个或多个值。当可能有许多变量/参数时,保持构造函数整洁。


我建​​议阅读:

XML序列化和反序列化:第1部分 [ ^ ]

XML序列化和反序列化:第2部分 [ ^ ]

自定义类集合序列化和反序列化的完整示例 [ ^ ]


这是我的建议:通过这个有问题的 XmlSerialize 。使用数据合同 DataContractSerialize - 使用起来更容易,完全非侵入式和数据无关,可以使用任意数据模型,而不是必然是树,等等。请参阅:

http://msdn.microsoft.com/en-us /library/ms733127.aspx [ ^ ],

https://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer%28v=vs.110%29.aspx [ ^ ]。



另见我过去的答案:

如何将数据合同从C#/ WCF代码传递给托管C ++ [ ^ ],

如何在我的表单应用程序中使用XML文件编写器和阅读器? [ ^ ],

创建属性文件...... [ ^ ],

反序列化列表< class object>导致objects属性失去对基类对象的引用 [ ^ ]。



-SA

I have three classes: person, address and phone. A person can have multiple addresses and each address has phone numbers. Here how to initialize and assign values multiple address and phone number. Below is my class model.

public class Person
{
    public string Name { get; set; }
    public string dob { get; set; }
    public List<Address> address { get; set; }
    public Person()
    {
        this.address = new List<Address>();
    }
}

public class Address
{
    public string street { get; set; }
    public string city { get; set; }
    public string pobox { get; set; }
    public string postalcode { get; set; }
    public Phone phone { get; set; }
    public Address()
    {
        this.phone = new Phone();
    }
}

public class Phone
{
    public string Mobile { get; set; }
    public string Landline { get; set; }
}

解决方案

Quote:

how to initialize and assign values multiple address and phone number.

There are several ways you can initialize/assign to whatever Collection data-structure you select to hold the multiple values. Here's an example that reflects the way I like to work:

public enum PhoneType
{
    Other,
    Home, Mobile
}

public enum AddressType
{
    Other,
    Home, Office, PO_Box
}

public class Person
{
    public string Name { get; set; }

    // see note on Constructor below
    public DateTime? Dob { get; set; }

    public Dictionary<PhoneType, List<int>> Phones { get; set; }
    public Dictionary<AddressType, List<Address>> Addresses { get; set; }

    public Person(string name,
        // use of nullable DateTime is a work-around
        // for the fact that a DateTime in a parameter
        // list must be a compile-time Constant
        DateTime? dob,

        // note the use of optional parameters here
        Dictionary<PhoneType, List<int>> phones = null,
        Dictionary<AddressType, List<Address>> addresses = null

        )
    {
        Name = name;
        // note use of null-coalsescing operator here
        Dob = dob ?? DateTime.MinValue;
        Phones = phones ?? new Dictionary<PhoneType, List<int>>();
        Addresses = addresses ?? new Dictionary<AddressType, List<Address>>();
    }

    public void AddPhone(PhoneType ptype , int number)
    {
        // requires Linq

        if(Phones == null) Phones = new Dictionary<PhoneType, List<int>>();

        // new type of Phone ? initialize with new List<int>
        if(! Phones.ContainsKey(ptype)) Phones.Add(ptype, new List<int>());
        
        // note: no check for duplicates here : implement check ?
        Phones[ptype].Add(number);
    }

    public void AddPhones(PhoneType ptype, List<int> phones)
    {
        if (Phones == null) Phones = new Dictionary<PhoneType, List<int>>();

        // new type of Phone ? initialize with new List<int>
        if (!Phones.ContainsKey(ptype)) Phones.Add(ptype, new List<int>());
        
        Phones[ptype].AddRange(phones);
    }

    public void RemovePhone(PhoneType ptype, int number)
    {
        // requires Linq

        var numbersbykey = Phones.FirstOrDefault(kvp => kvp.Key == ptype);

        if (numbersbykey.Value != null && numbersbykey.Value.Contains(number)) numbersbykey.Value.Remove(number);
    }

    //public void AddAddress(AddressType atype, string street, string city, string postalCode)
    //{
    //     // you write the code for this
    //}

    //public void RemoveAddress(AddressType atype, ???)
    //{
    //    // you write the code for this
    //}
}

Notes:

1. I like using Enums since they both help document the code and are easily expanded/altered in the future

2. I like using Dictionaries with Enum values as Keys when each Key will store multiple values

3. I like writing explicit Add methods for adding one, or many, values to a collection. Keeps the Constructor uncluttered when there may be many variables/parameters.


I'd suggest to read:
XML Serialization and Deserialization: Part-1[^]
XML Serialization and Deserialization: Part-2[^]
A Complete Sample of Custom Class Collection Serialization and Deserialization[^]


Here is my advice: through out this problematic XmlSerialize. Use much better Data Contract with DataContractSerialize — much easier to use, fully non-intrusive and data-agnostic, can work with arbitrary data model, not necessarily a tree, and so on. Please see:
http://msdn.microsoft.com/en-us/library/ms733127.aspx[^],
https://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer%28v=vs.110%29.aspx[^].

See also my past answers:
how to pass a datacontract from a C#/WCF code to Managed C++[^],
How can I utilize XML File streamwriter and reader in my form application?[^],
Creating property files...[^],
deserializing list<class object> cause the objects property lose their reference to the objects of the base class[^].

—SA


这篇关于列表对象创建和分配值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆