带有逻辑的c#私有Setter
本文关键字:私有 Setter | 更新日期: 2023-09-27 17:53:46
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Crystal_Message
{
class Person
{
private string firstName="";
private string lastName= "";
private string phone="";
public Person(string firstName, string lastName, string phone)
{
this.FirstName = firstName;
this.LastName = lastName;
this.PhoneNumber = phone;
}
public string FirstName
{
get { return firstName; }
set
{
if (string.IsNullOrWhiteSpace(this.firstName)){
throw new ArgumentNullException("Must Include First Name");
}
this.firstName = value;
}
}
public string LastName
{
get { return lastName; }
set
{
if (string.IsNullOrWhiteSpace(lastName)){
throw new ArgumentNullException("Must Include Last Name");
}
this.lastName = value;
}
}
public string PhoneNumber
{
get { return phone; }
set
{
if (string.IsNullOrWhiteSpace(phone)){
throw new ArgumentNullException("Must Include Phone Number");
}
this.phone = value;
}
}
public override string ToString()
{
return "First Name: " + this.FirstName + " " + " Last Name: " + this.LastName + " Phone Number: " + this.PhoneNumber;
}
}
}
我有一个简单的person类,它接受名字、姓氏和电子邮件。它对我有效,它不会被子类化。我正在构建一个小应用程序,person类是合适的。
我唯一的问题是,我如何实现一个私有 setter与内部逻辑,以确保值不是null或空?
只设置setter为私有。此外,您还有一个问题:
string.IsNullOrWhiteSpace(lastName)
将读取现有的属性值。您应该检查新提供的value
:
string.IsNullOrWhiteSpace(value)
最终代码: public string LastName
{
get { return lastName; }
private set
{
if (string.IsNullOrWhiteSpace(value)) {
throw new ArgumentNullException("Must Include Last Name");
}
lastName = value;
}
}
您可以为您的属性设置器使用私有修饰符:
public string FirstName
{
get { return firstName; }
private set
{
// Here you must check if value is not null or empty, not the field
if (string.IsNullOrWhiteSpace(value)){
throw new ArgumentNullException("Must Include First Name");
}
this.firstName = value;
}
}
在这种情况下,属性的setter将只能从同一个类访问。
有两种方法:
首先,您可以去掉set
,然后您的类可以对底层值进行操作:
public string FirstName
{
get { return firstName; }
}
}
// Then in your code:
this.firstName = "whatever"; // the local variable
或者您可以将setter的范围设置为private
:
public string FirstName
{
get { return firstName; }
private set
{
if (string.IsNullOrWhiteSpace(this.firstName)){
throw new ArgumentNullException("Must Include First Name");
}
this.firstName = value;
}
}