使用set在构造函数中更改属性值,c#



我写的程序工作正常,打印也很好。它创建了两个对象。一个对象将使用无参数默认构造函数创建,另一个对象将从非默认构造函数创建。唯一的区别是我应该为Author使用set关键字来创建默认值。所以当我用错误的作者名创建对象时它会使用set关键字来改变它。

当我为Book1输入错误的值时。对于非默认构造函数,它会更改两个对象中的Author名称。如何只允许它更改Book1对象中的作者名称?

using System;
namespace Book
{
public class Book
{
private string _Author;
private string _Title;
private string _Keywords;
private string _publicationDate;
private string _ISBN;
public Book()
{
Author = "";
}
public Book(string title, string author, string publicationDate, string keywords, string isbn)
{
Title = title;
Author = author;
Keywords = keywords;
PublicationDate = publicationDate;
ISBN = isbn;
}
public string Title { get => _Title; set => _Title = value; }
public string Author { get => _Author; set => _Author = "Mary Delamater and Joel Murach, "; }
public string Keywords { get => _Keywords; set => _Keywords = value; }
public string PublicationDate { get => _publicationDate; set => _publicationDate = value; }
public string ISBN { get => _ISBN; set => _ISBN = value; }
public override string ToString()
{
return Title + Author + PublicationDate + "Keywords: " + Keywords + "ISBN " + ISBN;


}


}
}
using System;
namespace Book
{
class Program
{
static void Main(string[] args)
{
Book Book1 = new Book("murach's ASP.NET Core MVC, ", "Mary Delamater and Joel Murach, ", "January 2020, ", "C#, Programming, MVC, ASP.NET, Core, Beginner", "978-1-943872-49-7");
Console.WriteLine(Book1.ToString());
Book Book2 = new Book();
Book2.Title = "C# In Depth, ";
Book2.Author = "John Skeet, ";
Book2.PublicationDate = "March 23, 2019, ";
Book2.Keywords = "C#, InDepth";
Book2.ISBN = "9781617294532";
Console.WriteLine(Book2.ToString());
}
}
}

您对程序流程的理解有误。在构造函数中,当您调用属性来设置值时,程序流将运行硬编码为字符串的set部分。现在,如果您尝试通过对象或构造函数通过此属性保存您的值,它将始终设置为硬编码值,而不管您想要什么。为了存储自定义值,您必须使用set=>value并应用业务约束,您可以在属性中编写逻辑条件,这就是为什么使用属性来实现封装。

像这样:

public string Author{
get{
return _Author;
}
set{
if()//your condition to validate if author is wrong
_Author = ""; //your expected correct author name
else
_Author = value
}
}

相关内容

  • 没有找到相关文章

最新更新