首页 > 解决方案 > 如何使用 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;
    }
}

标签: c#classoptional-parameters

解决方案


与其将其作为可选参数,不如使用不同的构造函数重载呢?而在第二个构造函数中,不要将 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;
    }
}

你没有问过这个问题,但是用空字符串初始化电子邮件并没有什么意义。最好将其默认为空。


推荐阅读