You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#模型Getter/Setter中ToString()方法报错求助

DateTime? 与字符串属性的Getter/Setter转换解决方案

原代码的核心错误

  • Getter类型不匹配:get => DateOfBirth 直接返回DateTime?类型给string?属性,编译不通过,必须先将DateTime?转换为字符串。
  • Setter方法误用:value.ToString("MMMM dd") 中value是string类型,string.ToString()没有接受格式字符串的重载,且逻辑上应该是将字符串转回DateTime?赋值给DateOfBirth,而非给私有字段赋值。

方案1:只读字符串属性(仅展示DateOfBirth的格式化结果)

如果DateOfBirthString仅用于展示DateOfBirth的格式化字符串,无需设置功能,可实现为只读属性:

public class PersonLookUpModel 
{ 
    public DateTime? DateOfBirth { get; set; }

    // 自动根据DateOfBirth生成格式化字符串,null时返回null
    public string? DateOfBirthString => DateOfBirth?.ToString("MMMM dd");
}

方案2:支持读写的双向转换

如果需要通过DateOfBirthString设置DateOfBirth的值,同时Getter返回格式化字符串,可实现如下:

using System.Globalization;

public class PersonLookUpModel 
{ 
    private DateTime? _dateOfBirth;

    public DateTime? DateOfBirth 
    { 
        get => _dateOfBirth; 
        set => _dateOfBirth = value; 
    }

    public string? DateOfBirthString 
    { 
        get => _dateOfBirth?.ToString("MMMM dd"); 
        set 
        {
            // 用TryParseExact确保严格匹配格式,避免转换错误
            if (!string.IsNullOrEmpty(value) && DateTime.TryParseExact(
                value, 
                "MMMM dd", 
                CultureInfo.InvariantCulture, 
                DateTimeStyles.None, 
                out DateTime parsedDate))
            {
                _dateOfBirth = parsedDate;
            }
            else
            {
                _dateOfBirth = null;
            }
        }
    }
}

关键说明

  • 使用?.空条件运算符:避免DateOfBirth为null时调用ToString()引发空引用异常。
  • 格式转换的严谨性:如果外部传入的字符串格式固定,推荐用DateTime.TryParseExact替代TryParse,减少格式不匹配导致的转换失败。

内容的提问来源于stack exchange,提问作者tom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 00:43:26