我的问题是:在创建新对象后,有没有办法可以访问构造函数属性。
我创建了这个类:
class Book
{
private string Title { get; set; }
private string Author { get; set; }
private string ISBN { get; set; }
public bool Available { get; set; }
public Book(string title, string author, string isbn)
{
this.Title = title;
this.Author = author;
this.ISBN = isbn;
}
}
然后我以下列方式创建一个新对象:
Book myBook = new Book("Strategic Management", "John Doe", "1234567");
如何从上面的对象中提取标题?我需要在以下语法中使用Title:
public void RemoveLoan(Book oldLoan)
{
var item = Loans.SingleOrDefault(x => x.Book.Title == oldLoan.Title);
if (item != null)
{
Loans.Remove(item);
}
}
提前致谢
答案 0 :(得分:2)
通常,只有setter
方法封装在属性中:
// setter is encapsulated, while getter is public allowing you to acess value
public string Title { get; private set; }
public string Author { get; private set; }
public string ISBN { get; private set; }
或者,您可以使用readonly
字段制作课程immutable:
public readonly title;
public readonly author;
public readonly iSBN;