如何解决“无法分配给'this',因为它是只读的”错误 c#

How to solve a "cannot assign to 'this' as it is readonly" error c#

提问人:Muffin 提问时间:4/4/2022 更新时间:4/4/2022 访问量:333

问:

我正在创建一个类,该类使用 DataTable 创建我自己的自定义表。

我想要它,以便如果带有 DataTable 信息的 json 文件在我的计算机上;该代码会将 JSON 文件放入对象的该实例中(在构造函数中完成)

这就是我试图做到的

public Table(string jsonfile)
    {
        if(File.Exists(jsonfile))
        {
            this = JsonConvert.DeserializeObject<Table>(File.ReadAllText(jsonfile));
            return;
        }
        formatRegisterTable(jsonfile);
    }

此行导致错误

this = JsonConvert.DeserializeObject<Table>(File.ReadAllText(jsonfile));

我怎样才能做到这一点而不会出现错误?

如果需要,类的完整代码:

using System.IO;
using System.Data;
using Newtonsoft.Json;

namespace abc.classess._table
{
     class Table
    {
        public DataTable mTable = new DataTable("table");
        private DataColumn mColumn;
        private DataRow mRow;
        

        public Table(string jsonfile)
        {
            if(File.Exists(jsonfile))
            {
                this = JsonConvert.DeserializeObject<Table>(File.ReadAllText(jsonfile));
                return;
            }
            formatRegisterTable(jsonfile);
        }

        private void formatRegisterTable(string jsonfile) 
        {
            //formatting table code

            File.WriteAllText(jsonfile,JsonConvert.SerializeObject(this));
        }
    }
}
C# JSON 数据表 编译器 - 错误

评论

0赞 Serge 4/4/2022
你能发布你的json吗?
2赞 Charles Mager 4/4/2022
不能分配给 。反序列化器返回一个新的 .在此类之外执行此操作或创建方法。thisTablestatic Table Load(string fileName)
0赞 Kirk Woll 4/4/2022
@CharlesMager,好吧,从技术上讲,如果 OP 的代码是一个结构,它就会起作用,而不是我建议这样做。

答:

2赞 Somar Zein 4/4/2022 #1

像这样的东西应该可以解决你的问题:

在类中创建以下函数:Table

 public static Table Create(string jsonfile)
 {
       if (File.Exists(jsonfile))
       {
            Table table = JsonConvert.DeserializeObject<Table>(File.ReadAllText(jsonfile));
            return table;
        }
        
        return new Table(jsonfile);
  }

您的表构造函数现在应如下所示:

 public Table(string jsonfile)
 {
    formatRegisterTable(jsonfile);
 }

然后,您可以在代码中使用它var newTable = Table.Create(jsonFile);

评论

0赞 Muffin 4/4/2022
我了解到,在声明新的对象实例(从我创建的类中)时,我不仅使用“new”初始化它们,然后使用构造函数;但如果需要,我可以使用不同的方法进行初始化