简体   繁体   English

如何将我的数据保存在 .txt 文件中,析构函数不起作用?

[英]How do I save my data on .txt file, destructor doesn't work?

On my last try every adding section it adds 3x data on data.txt在我最后一次尝试每个添加部分时,它会在 data.txt 上添加 3x 数据

I think that I can do my save on my destructor method but it doesn't work.我认为我可以保存我的析构函数方法,但它不起作用。

data format consists of 3 string expression likes: date + soccer team + country数据格式由 3 个字符串表达式组成,例如:日期 + 足球队 + 国家

This is a section from my DataStructor class这是我的 DataStructor class 的一部分

takimlar.Add("1905", "GS", "TR");


internal class Node
        {
            internal T ulke;
            internal T takim;
            internal T tarih;
            internal Node next = null;
            internal Node pre = null;
            internal Node(T tarih, T takim, T ulke)
            { this.tarih = tarih; this.takim = takim; this.ulke = ulke; }
        }
internal IEnumerable<string> GetEnumerator()
        {
            for (Node traveler = first; traveler != null; traveler = traveler.next)
               yield return $"{traveler.tarih},{traveler.takim},{traveler.ulke}";
        }
internal IEnumerable<Node> GetEnumeratorNodeUlke(T ulke)
        {
            for (Node traveler = first; traveler != null; traveler = traveler.next)
                if (traveler.ulke.Equals(ulke))
                    yield return traveler;
        }

How it can be fixed?如何修复?

using System;
using System.Windows.Forms;
using System.IO;
using System.Linq;
using System.Collections.Generic;

namespace TAKIM_ULKE
{
    internal partial class MainForm : Form
    {
        AdderForm adderForm = new AdderForm();
        static string filePath = @"C:\Users\nevfe\source\repos\TAKIM_ULKE\TAKIM_ULKE\bin\Debug\netcoreapp3.1\data.txt";
        List<string> lines = new List<string>();
        List<string> output = new List<string>();
        
        internal MainForm()
        {
            InitializeComponent();

            lines = File.ReadAllLines(filePath).ToList();
            foreach (string line in lines)
            {
                string[] entries = line.Split(',');
                adderForm.takimlar.Add(entries[0], entries[1], entries[2]);
            }

            foreach (var item in adderForm.takimlar.GetEnumeratorUlke())      //Ülkeleri listele
                ulkeComboBox.Items.Add(item);
        }
        ~MainForm()
        {
            foreach (string item in adderForm.takimlar.GetEnumerator())
                if (!lines.Contains(item))
                    output.Add(item);

            File.WriteAllLines(filePath, output);
        }
     }
}

The problem with the destructor, also known as Finalizer, is that it is called when the object goes out of scope and collected by the garbage collector.析构函数(也称为终结器)的问题在于,当 object 超出 scope 并被垃圾收集器收集时,会调用它。

This means that C# works differently compared to some other languages.这意味着与其他一些语言相比,C# 的工作方式不同。

The purpose is to clean up and free any resources, normally in the destructor this should be unhandled resources.目的是清理和释放任何资源,通常在析构函数中这应该是未处理的资源。 This means that you should not be executing "business logic" such as writing to files in a destructor.这意味着您不应该执行“业务逻辑”,例如在析构函数中写入文件。

There is also no guarantee that the destructor will be called at all or when it will be called.也不能保证析构函数将被调用或何时被调用。 Because the GC does not necessarily destroy objects at the exact moment they go out of scope, but waits until it is convenient.因为 GC 不一定会在他们 go 出 scope 的确切时刻销毁对象,而是等到方便的时候。

There are several other posts about this which you can read in more detail if you wish, where others have explained this much better than I can!如果您愿意,还有其他几篇关于此的帖子,您可以更详细地阅读,其他人对此的解释比我好得多!

Why does my destructor never run? 为什么我的析构函数从不运行?

When should I create a destructor? 我应该什么时候创建析构函数?

So then how should you solve this?那么你应该如何解决这个问题呢?

Well, reading the posts, you will see that a better solution is to use the IDispose pattern.好吧,阅读帖子,您会发现更好的解决方案是使用 IDispose 模式。 But this is also really designed to clean-up after you have finished with the object.但这也是为了在您完成 object 后进行清理而设计的。 As you still need to execute business logic, then IMHO this is still not the right place.由于您仍然需要执行业务逻辑,那么恕我直言,这仍然不是正确的地方。

So then you should be looking at the Events of the Winform.因此,您应该查看 Winform 的事件。 So if we look at the Winform lifecycle here https://docs.microsoft.com/en-us/dotnet/desktop/winforms/order-of-events-in-windows-forms?view=netframeworkdesktop-4.8因此,如果我们在这里查看 Winform 生命周期https://docs.microsoft.com/en-us/dotnet/desktop/winforms/order-of-events-in-windows-forms?view=netframeworkdesktop-4.8

Then we see that we have several options when closing the form / application, so you can select the one which suits you.然后我们看到在关闭表单/应用程序时我们有几个选项,因此您可以选择适合您的 select。

I would suggest, if you need to cancel the form closing (eg if writing fails), then use Form.Closing .我建议,如果您需要取消表单关闭(例如,如果写入失败),请使用Form.Closing Else use Form.Closed .否则使用Form.Closed

Your destructor may not be called at all due to application closing.由于应用程序关闭,您的析构函数可能根本不会被调用。
Use FormClosing event.使用FormClosing事件。

Read more here. 在这里阅读更多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何重写txt文件-为什么我的代码不起作用 - How to rewrite txt file-why my code doesn't work 我的if else陈述似乎无效。 如何防止将空数据发送到数据库? - My if else statement doesn't seems to work. How do I prevent sending empty data to the Database? 我需要将多个项目保存在 a.txt 文件中的 List&lt;&gt; 中,我该怎么做? 我没有任何代码可以显示 atm :') - I need to save multiple items in a List<> in a .txt file, how can I do that? I don't have any code to show atm :') 如何在数据库中保存数据? - How do I save data in my database? 如何在 C# 中的记事本 .txt 文件中添加数据? - How Do I add data in the notepad .txt file in C#? 如何将txt文件保存在项目中的其他文件夹中? - How do I save a txt file inside a different folder within the project? 我尝试使用 WP7 中的隔离存储在 txt 文件中保存许多行,但它只会保存一个,我如何保存很多行? - I try to save many lines in a txt file using isolated storage in WP7 but it will only saves one, how do I save many? Unity3D无法从XML文件保存和加载数据 - Unity3D Save and Load data from an XML file doesn't work SQLite不保存我插入的数据 - SQLite doesn't save data I inserted 我的“数据默认值(getdate())”,它不起作用 - My “data default (getdate())”, it doesn't work
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM