c# - 如何使用 DateTime.Now.Year 作为可选参数的默认值
问题描述
你能告诉我如何解决这个错误吗
默认参数值必须是编译时常量"
我知道这个问题,并且已经在 Stack Overflow 上看到了方法的解决方案,但我不知道如何为类解决这个问题。
public class member
{
public string name { get; }
public string email { get; set; }
public int entryYear;
static int memberNbr;
public member (string _name, int _entryyear = DateTime.Now.Year, string _email = "")
{
name = _name;
entryyear = _entryyear;
email = _email;
}
}
解决方案
与其将其作为可选参数,不如使用不同的构造函数重载呢?而在第二个构造函数中,不要将 entryYear 作为参数,而是在构造函数体中对其进行初始化?
当我们这样做时,让我们使用正确的 C# 约定,例如属性名称为 PascalCase,构造函数参数为驼峰式。并且不使用属性名称的缩写,并且当 MemberNumber 明显属于单个实例时不要将其设为静态。
public class Member
{
public string Name { get; }
public string Email { get; }
public int EntryYear { get; }
public int MemberNumber {get; }
public Member(string name, int entryYear, string email = "")
{
Mame = Name;
EntryYear = entryYear;
Email = email;
}
public Member(string name, string email = "")
{
Mame = Name;
EntryYear = DateTime.Now.Year;
Email = email;
}
}
你没有问过这个问题,但是用空字符串初始化电子邮件并没有什么意义。最好将其默认为空。
推荐阅读
- arrays - 使用某些东西是一种不好的做法吗?.isEmpty == true
- r - fsolve 在没有解决方案时给出错误 + 帮助我回溯错误消息
- javascript - 以正确的方式调用模板
- c# - 动画总是改变对象位置
- git - 将 Git 存储库复制到具有提交历史记录的现有存储库的子目录中
- python - 没有名为“stocker”的模块
- elasticsearch - 在 Elasticsearch 中匹配两个过滤条件
- mariadb - 硬链接/软链接不适用于 MariaDB 上的 my.cnf
- html - 我想在没有 CSS 的情况下在网页的两侧创建空间
- dart - StreamController 和 BehaviorSubject 是 Dart 中的流吗?