属性 或索引器 'NodaTime.LocalDateTime.Month' 无法分配给 -- 它是只读的

Property or indexer 'NodaTime.LocalDateTime.Month' cannot be assigned to -- it is read only

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Reflection;
using System.IO;
using NodaTime;

namespace MyApp
{
    public partial class MainForm : Form
    {
        public class Foo
        {
            private LocalDateTime date_time;

            public Foo(string data)
            {
                Int32 i;
                char[] delimiters = { ',', '/', ':' };
                string[] tokens = data.Split(delimiters);

                if( Int32.TryParse(tokens[0], out i ))
                {
                    date_time.Month = i;
                }
            }
        };

        public MainForm()
        {
            InitializeComponent();
        }
    }
}

我将 date_time.Month 设置为 i 的行是我在标题中指出错误的地方 - 属性 或索引器无法分配给 - 它是只读的。我搜索了很多类似的帖子,但找不到解决方案。任何帮助将不胜感激。提前致谢!

如果 LocalDateTime 是可变的,你可以这样做:

LocalDateTime x = new LocalDateTime();
x.Year = 2016;
x.Month = 4;
x.Day = 20;
x.Hour = 11;
x.Minute = 30;

但是,它是不可变的。它是 不可变的 。因此,你必须这样做:

LocalDateTime x = new LocalDateTime(2016, 4, 20, 11, 30);

在您的代码中,您在 class 中定义了一个字段 date_time,并将其声明为 LocalDateTime 类型,但您从未为其赋值.由于此类型是 struct,因此将使用其默认值进行初始化,对于 LocalDateTime1970-01-01 00:00:00

然后您尝试设置一个 属性,好像该值是可变的,但它是不可变的,所以没有 setter。相反,您需要将 LocalDateTime 结构的新实例分配给该字段,类似于我上面显示的方式。

还认识到 Noda Time 具有广泛的内置解析功能,因此无需将字符串拆分为组件或尝试将它们解析为整数。例如:

using NodaTime;
using NodaTime.Text;

...

var pattern = LocalDateTimePattern.CreateWithInvariantCulture("M/d/yyyy HH:mm:ss");
var result = pattern.Parse("4/20/2016 11:30:00");
if (!result.Success)
{
    // handle error
}

LocalDateTime ldt = result.Value;

如果您要解析很多值,您可以在静态变量中保留 pattern 实例,以避免每次都必须创建它。这提供了比 DateTime.ParseExact.

等等效 BCL 方法更好的性能