首页 > 解决方案 > c#程序中类结构接口中的无效标记'='

问题描述

using System.Text;
using System.Threading.Tasks;

namespace Program
{
    public class Book
    {
        public string title;
        public string author;
        public int pages;
        Book.pages = 10;
    }
}

我不确定为什么会收到无效令牌错误。请帮忙。

标签: c#

解决方案


如果要为页面设置默认值,可以使用此代码。

public class Book
{
    public string title { get; set; }
    public string author { get; set; }
    public int pages { get; set; } = 10;
}

但是如果你想在创建你的类之后设置值,你可以使用这个代码:第一次你应该创建你的对象的实例并设置值。

public class Book
{
    public string title { get; set; }
    public string author { get; set; }
    public int pages { get; set; }
}
Book book = new Book { pages = 10 };

您还可以使用constructor设置默认值。

public class Book
{
    public Book()
    {
        this.pages = 10;
    }
    public string title { get; set; }
    public string author { get; set; }
    public int pages { get; set; } 
}

推荐阅读