gpt4 book ai didi

具有逻辑的 C# 私有(private) Setter

转载 作者:太空宇宙 更新时间:2023-11-03 18:05:45 25 4
gpt4 key购买 nike

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 类很合适。

我唯一的问题是,如何使用内部逻辑实现一个private setter,以确保该值不为空或不为空?

最佳答案

仅将 setter 设为私有(private)。另外,你有一个问题:

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

关于具有逻辑的 C# 私有(private) Setter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30685795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com