开发者

Setting a variable - constructor/get/set C#

开发者 https://www.devze.com 2023-04-10 13:41 出处:网络
i haven programmed in a while so i forgot something. ive 开发者_运维知识库got a \"Kunde\" class. with some variables:

i haven programmed in a while so i forgot something.

ive 开发者_运维知识库got a "Kunde" class. with some variables:

class Kunde
{
    private string _navn;
    private string _adresse;
    private int _postnr;
    private string _by;
    private int _telefonnr;
    private int _mobil;
    private string _email;
    private string _land;
    private string _oplysning;
    private int _kundenr;
    //Erhverv:
    private int _cvr;
    private string _firmanavn;
    private string _kontaktperson;

    //Tom konstruktør
    public Kunde()
    {
    }

    //privat
    public Kunde(string navn, string adresse, int postnr, string by, int telefonnr, int mobil, string email, string land, string oplysning, int kundenr)
    {
        _navn = navn;
        _adresse = adresse;
        _postnr = postnr;
        _by = by;
        _telefonnr = telefonnr;
        _mobil = mobil;
        _email = email;
        _land = land;
        _oplysning = oplysning;
        _kundenr = kundenr;
    }
}

}

my question is.. ive got a winform with some text fields, but not every field has to be filled with data..

should a make a get/set on every variable to be able to set the variable from another class - or a constructor for each option?

whats the best way to do this?


Just provide a Get and optionally a Set accessor for each member.

You'll have to pick some form of DataBinding + Validation to work from your Form. But a Customer class has its own design and its own logic.


In C# 4.0, you can specify values for properties when calling a constructor.

var kunde = new Kunde() 
{
    Navn = navn,
    Adresse = adresse,
    // all your properties
};

Create get/set accessors for each of your fields and then you can specify whichever properties you want to set as above.


You'd better keep default constructor only and create public property for each data you need to read or set.

You may keep your constructor with parameters - but only with those that are really mandatory to be filled for each of your Kunde-n.

If you plan to bind your Kunde object-s directly to some BindingSource and display them e.g. in some sort of grid/list and/or treeview you may also consider implementing some of the related interfaces: System.ComponentModel.IdataErrorInfo; System.ComponentModel.INotifyPropertyChanged;

and you may cosider apply Attribute-s to your public properties - such as System.ComponentModel.DisplayNameAttribute; - it can define fixed name of headers in the DataGrid orit might be localized for different languages


public string Adresse { get; private set; } etc. and you have an automatic variable which is read-only except inside the class.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号