【发布时间】:2023-08-18 15:36:01
【问题描述】:
我的完整问题是:
当我在属性中创建条件时,我是否必须再次在自定义构造函数中创建相同的条件,或者我可以以某种方式使用属性自定义构造函数?
如果我有这样的代码:
class Program
{
struct Student
{
private int _id;
private string _name;
private int _age;
public int ID // Property
{
get
{
return _id;
}
set
{
if (value <= 0)
{
Console.WriteLine("You cannot assign id less then 1");
Console.ReadLine();
Environment.Exit(0);
}
else
{
_id = value;
}
}
}
public string NAME // Property
{
get
{
return _name;
}
set
{
if (String.IsNullOrEmpty(value))
{
_name = "No Name";
}
else
{
_name = value;
}
}
}
public int AGE // Property
{
get
{
return _age;
}
set
{
if(value <= 0)
{
Console.WriteLine("Your age cannot be less then 1 year.");
Console.ReadLine();
Environment.Exit(0);
}
else
{
_age = value;
}
}
}
public Student(int initID, string initName, int initAge) // Defining custom constructor
{
if (initID <= 0)
{
Console.WriteLine("You cannot assign id less then 1");
Console.ReadLine();
Environment.Exit(0);
}
if (String.IsNullOrEmpty(initName))
{
_name = "No Name";
}
if (initAge <= 0)
{
Console.WriteLine("Your age cannot be less then 1 year.");
Console.ReadLine();
Environment.Exit(0);
}
_id = initID;
_name = initName;
_age = initAge;
}
public void Status() // struct member - method
{
Console.WriteLine("ID: {0}", _id);
Console.WriteLine($"Name: {_name}");
Console.WriteLine($"Age: {_age}\n");
}
}
static void Main(string[] args)
{
Student s1 = new Student(1, "James", 10);
s1.Status();
Console.ReadLine();
}
}
如您所见,我在属性中设置了一些条件,例如 ID 不能为 0 且小于 0,但是当我想使用自定义构造函数时,我必须再次设置此条件。这是唯一的方法如何做到这一点?还是其他方式?
自定义构造函数是否与封装一起使用?当你有属性时?
感谢您的回答。 :)
【问题讨论】:
-
您的第一个问题是您使用的是
struct而不是class。你应该有一个很好的理由这样做。您很少需要使用struct。
标签: c# if-statement struct properties encapsulation