簡體   English   中英

在實例化之前設置屬性默認值

[英]Set property default value before instantiation

我有一班學生:

public class Student
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

當我創建一個Student類的實例時,它為null。

Student s = new Student();

s.ID為nulls.Name為nulls.Age為null 。”

我想為Student類設置一個默認值,所以當我創建它的實例時:

Student s = new Student();

s.ID = 1s.Name = Parsas.Age = 20

換句話說,我想更改聲明或實現屬性getter或重寫它

我怎樣才能做到這一點 ?

更新資料

我KHOW我能做到這一點與靜態類或定義Constractor,但我沒有訪問學生類,我希望它不是靜態的。 我認為這個問題可以通過反射解決

先感謝您。

您必須將字段初始化為您想要的默認值。 例如:

class MyClass
{
    int value = 42;

    public int Value
    {
        get {return this.value;}
        set {this.value = value;}
    }
}

您可以使用DefaultValue屬性將此非零默認值告知設計者:

class MyClass
{
    int value = 42;

    [DefaultValue(42)]    
    public int Value
    {
        get {return this.value;}
        set {this.value = value;}
    }
}

由於您無權訪問Student類,因此只需將您的類包裝到具有獲取和設置Student類的屬性的屬性中,然后將其包裝到另一個類中,並在新的類構造函數中根據需要定義默認值。

簡單地創建一個分配了默認值的構造函數:

public Student(){
   this.ID = 1;
   this.Name = "Some name";
   this.Age = 25;
}

當我創建一個Student類的實例時,它為null。

“ s.ID為null,s.Name為null,s.Age為null。”

首先, AgeID不能為null,因為它們是值類型而不是引用類型。

其次,成員變量不返回任何有用的數據,因為屬性未初始化,因此對於數字類型,它將為0,對於引用類型,它將為null。

我想為Student類設置一個默認值,所以當我創建它的實例時:

學生s =新的Student(); “ s.ID = 1,s.Name = Parsa,s.Age = 20”

我可以想到三種解決方案:

解決方案-1:對象初始化程序

Student student = new Student { ID = 1, Name = "Parsa", Age = 20 }; // from C# 3.0

解決方案2:自動屬性初始化程序

public class Student{
     public int ID { get; set; } = 1; 
     public int Name { get; set; } = "Parsa"; // C# 6 or higher
     public int Age { get; set; } = 20;
}

解決方案3:使用構造函數

public class Student
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }

    public Student(int id, String name, int age){
       this.ID = id;
       this.Name = name;
       this.Age = age;
    }
}

這樣稱呼它:

Student s = new Student(1,"Parsa",20);
{
    private int _id = 0;
    public int ID
    {
        get
        {
            return _id;
        }
        set
        {
            _id = value;
        }
    }
    private string _Name = string.Empty;
    public string Name 
    {
        get
        {
            return _Name;
        }
        set
        {
            _Name = value;
        }
    }

    private int _Age = 0;
    public int Age 
    {
        get
        {
            return _Age;
        }
        set
        {
            _Age = value;
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM