在实例化之前设置属性默认值

时间:2017-03-23 21:05:00

标签: c# reflection orm

我有一个名为Student的课程:

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

当我创建Student类的instanse时,它为null。

Student s = new Student();

s.ID为空 s.Name为空 s.Age为空。”

我想为Student类设置一个默认值,所以当我创建它的实例时:

Student s = new Student();

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

换句话说,我想更改属性getter的声明或实现或覆盖它

我该怎么做?

更新

我知道我可以使用Static类或定义Constractor,但是我没有访问Student类,我想要它Not-Static。 我认为这个问题可以通过反射

来解决

先谢谢你。

5 个答案:

答案 0 :(得分:2)

您必须将字段初始化为默认值。例如:

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;}
    }
}

答案 1 :(得分:1)

由于您无法访问Student类,因此您只需将您的类包装到另一个类中,该类具有获取和设置Student类属性的属性,并在新类构造函数内定义默认值。

答案 2 :(得分:1)

简单地创建一个分配了默认值的构造函数:

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

答案 3 :(得分:0)

  

当我创建Student类的instanse时,它为null。

     

" s.ID为null,s.Name为null,s.Age为null。"

首先,AgeID不能为空,因为它们的值类型不是引用类型。

其次,成员变量不会返回任何有用的数据,因为属性未初始化,因此对于数字类型,它将为0,对于引用类型,它将为null。

  

我想为Student类设置一个默认值,所以当我创建时   它的实例:

     

学生s =新学生(); " 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);

答案 4 :(得分:0)

{
    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;
        }
    }
}