我可以和如何使用自定义类作为数据类型?

时间:2014-09-18 01:25:32

标签: c# winforms

我需要在c#中创建一个小型地址簿应用程序。表单包含姓名,地址,城市,州和邮政编码的输入。保存后需要进入列表框。该应用程序包含2个自定义类(地址和朋友)。查看类图,看起来Address类是Friend类中位置的数据类型。我可以使用自定义类Address作为朋友类的数据类型吗?地址类具有地址,城市,州,邮政编码的字段,而朋友类具有名称字段。我收集了Friend类中的字段位置从Address类的所有字段中获取其信息,但我不知道如何将该信息提供给Friend类和列表框。希望这个问题不会太混乱。我现在不太担心这一部分的照片部分。 朋友班:

namespace Friends
{
public class Friend
{
    #region [Fields]
    private string _name;
    private Address _location;
    private string _photo;
    #endregion

    #region [Properties]
    public string Name 
    {
        get { return _name; }
        set 
        {
            if (value == null)
                throw new ArgumentNullException("Name", "Please enter a name");
            _name = value.Trim();
        }
    }
    public Address Location { get; set }
    public string Photo
    {
        get { return _photo; }
        set { _photo = null;}
    }
    #endregion
    #region Constructors
    public Friend()
    {
        this.Name = String.Empty;
        this.Photo = null;
    }
    public Friend(string name)
    {
        this.Name = name;
        this.Photo = null;
    }
    public Friend(string name, Address location)
    {
        this.Name = name;
        this.Location = location;
        this.Photo = null;
    }
    #endregion

    #region Methods

    public override string ToString()
    {
       return this.Name + " -- " + this.Location;
    }
    #endregion
    }
}

不起作用的代码背后的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using PersonInfo;


namespace Friends
{
public partial class Form1 : Form
{
    List<Friend> myFriend = null;
    public Form1()
    {
        InitializeComponent();
        myFriend = new List<Friend>();
    }

    private void btnSave_Click(object sender, EventArgs e)
    {
        Friend f = new Friend()
        {               
            f.Name = txtName.Text,
            f.Location.Street = txtAddress.Text,
            f.Location.City = txtCity.Text,
            f.Location.State = txtState.Text,
            f.Location.Zip5 = txtZip.Text                
        };                            

        lstContacts.Items.Add(f);

    }

    private void btnExit_Click(object sender, EventArgs e)
    {
        Application.Exit();
    }
}
}

如果这个问题需要更多澄清或需要分成单独的问题,请告诉我。

3 个答案:

答案 0 :(得分:2)

您需要覆盖ToString类上的Address,以便它也可以呈现自己的输出:

public class Address {
    // .. other code here

    public override string ToString() {
        return string.Join(",", this.AddressLine, this.City, this.Suburb, this.State, this.Postcode);
    }
}

这将导致:Name - AddressLine, City, Suburb, State, Postcode(具有适当的值)

您可能还需要在ToString课程中致电Friend

public class Friend {
    // ...other code here

    public override string ToString() {
        return this.Name + " -- " + this.Location.ToString(); // <-- this
    }
}

此外,您需要在第一个构造函数中初始化Location属性,以避免抛出NullReferenceException

public Friend(string name) {
    // .. other stuff here
    this.Location = new Address();
}

答案 1 :(得分:0)

您的问题不太清楚且易于理解。我认为你想要做的是能够以关系的方式获得用户的朋友的地址信息。

我会尝试解释它,但如果我不理解你的问题是正确的,请澄清你想要确切知道的内容。

注意:我使用自动属性来保持代码示例的简短。

这是你的人类:

public class Person
{
    public string Name { get; set; }
    public AddressInfo Address { get; set; }
    public List<Person> Friends { get; set; }

    public Person()
    {
        //Avoid object reference not set exception.
        Friends = new List<Person>();
    }
}

用于建模地址的AddressInfo类。

public class AddressInfo
{
    public int ZipCode { get; set; }
    public string Adress { get; set; }
    //More fields can be added if necessary.
}

要实例化具有地址的人:

Person newRecord = new Person();
newRecord.Name = "John Smith";
newRecord.Address = new AddressInfo();
newRecord.Address.ZipCode = 1234;
newRecord.Address.Address = "Sesame street.";

如果您想将两个人关联为朋友,您只需将该人添加到其他朋友的收藏中。

Person myFriend = new Person();
myFriend.Name = "John Doe";
myFriend.Address = new AddressInfo { ZipCode = 1234, Address = "Some street..." };

newRecord.Friends.Add(myFriend);

我希望你能在这里获得对象之间的关系。当你需要一个人的朋友时,你只需要遍历&#34;朋友&#34;收集所述人物。

如果您使用Linq,您还可以查询Friends集合。例如:myPerson.Friends.Where(f =&gt; f.Name ==&#34; John Doe&#34;)。FirstOrDefault();

至于持久性,如果您正在使用数据库(如SQL Server),您可能希望将Entity Framework用作ORM(http://msdn.microsoft.com/en-us/data/ef.aspx),或者用于桌面应用程序,如地址簿I&建议您使用XML文件在设备之间轻松移植联系人列表。

希望这有用。

答案 2 :(得分:-1)

是的,您可以这样使用:

    using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;


    public class Friend: IValidatableObject

    {
        [Required]
        public string Name { get; set; }

        public string Photo { get; set; }

        public Address Location { get; set; }

       public override string ToString()
       {
         return  string.Format("{0}{1}{2}{3}", this.Location.Line1, this.Location.City, this.Location.State, this.Location.Zip);
       }
        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            var results = new List<ValidationResult>();

            var isValid = Validator.TryValidateObject(this, validationContext, results);

            if (!isValid)
            {
                foreach (var validationResult in results)
                {
                    results.Add(validationResult);
                }
            }

            return results;
        }
    }





public class Address
{
    public string Line1 { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Zip { get; set; }
}

Neet and simple。

对于验证,您可以调用Validate Method或使用Modelstate.isvalid。