C# でオブジェクトを削除する
Muhammad Maisam Abbas
2024年2月16日
Csharp
Csharp Object

このチュートリアルでは、C# でユーザー定義クラスのオブジェクトを削除する方法について説明します。
null
値を割り当てることにより、C# でユーザー定義のクラスオブジェクトを削除する
クラスオブジェクトは、そのクラスのメモリ位置を指す参照変数です。null
値を割り当てることで、オブジェクトを削除できます。これは、オブジェクトに現在、メモリ位置への参照が含まれていないことを意味します。次の例を参照してください。
using System;
namespace delete_object {
public class Sample {
public string value { get; set; }
}
class Program {
static void Main(string[] args) {
Sample x = new Sample();
x.value = "Some Value";
x = null;
Console.WriteLine(x.value);
}
}
}
出力:
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
上記のコードでは、Sample
クラスのオブジェクト x
を初期化し、value
プロパティに値を割り当てました。次に、null
を x
に割り当ててオブジェクトを削除し、x.value
プロパティを出力しました。x
はどのメモリ位置も指していないため、例外が発生します。
もう 1つの有益なアプローチは、オブジェクトを削除した後でガベージコレクターを呼び出すことです。このアプローチは、以下のコード例に示されています。
using System;
namespace delete_object {
public class Sample {
public string value { get; set; }
}
class Program {
static void Main(string[] args) {
Sample x = new Sample();
x.value = "Some Value";
x = null;
GC.Collect();
Console.WriteLine(x.value);
}
}
}
上記のコードでは、C# の GC.Collect()
メソッドを使用して x
オブジェクトに null
値を割り当てた後、ガベージコレクターを呼び出しました。
チュートリアルを楽しんでいますか? <a href="https://www.youtube.com/@delftstack/?sub_confirmation=1" style="color: #a94442; font-weight: bold; text-decoration: underline;">DelftStackをチャンネル登録</a> して、高品質な動画ガイドをさらに制作するためのサポートをお願いします。 Subscribe
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn