c# - 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;
}
}
我不确定为什么会收到无效令牌错误。请帮忙。
解决方案
如果要为页面设置默认值,可以使用此代码。
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; }
}
推荐阅读
- python - 检查所有值是否作为字典中的键存在
- html - 光滑的轮播内容不显示
- css - 多种后代类型的 CSS 选择器#example> div,p,a{}
- javascript - 在一个函数中设置两次状态 - ReactJS
- python - 使用 numpy 乘法后的多项式值错误
- logstash - 在线 grok 调试器无法按预期工作
- c++ - VS2017 中的字符串赋值行为
- ubuntu - 如何将 .war 从 docker-composer 移动到主机的值文件夹?
- react-native - 反应本机:TypeError:网络请求失败
- haskell - Yesod 子站点函数处理程序