[英]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为null , s.Name为null , s.Age为null 。”
我想为Student类设置一个默认值,所以当我创建它的实例时:
Student s = new Student();
“ s.ID = 1 , s.Name = Parsa , s.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。”
首先, Age
和ID
不能为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.