私は簡単なプログラムを持っています:
using System;
using System.Reflection;
namespace PlayWithReflection
{
class MyDisposable:IDisposable
{
private string _name;
public MyDisposable(string name)
{
this._name = name;
}
public string Name
{
get { return _name; }
}
public void Dispose()
{
Console.WriteLine(_name + " is disposed");
}
}
class MyBaseClass : IDisposable
{
protected MyDisposable _baseProtectedDisposableA = new MyDisposable("_baseProtectedDisposableA");
private MyDisposable _baseDisposableB = new MyDisposable("_baseDisposableB");
public MyDisposable BaseProtectedDisposableA
{
get { return _baseProtectedDisposableA; }
}
public MyDisposable BaseDisposableB
{
get { return _baseDisposableB; }
}
public void Dispose()
{
var fieldInfos = this.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy);
foreach (var fieldInfo in fieldInfos)
{
var value = fieldInfo.GetValue(this);
if (value is IDisposable)
{
((IDisposable)value).Dispose();
fieldInfo.SetValue(this, null);
}
}
}
}
class MyClass : MyBaseClass
{
private MyDisposable _disposableC = new MyDisposable("_disposableC");
private MyDisposable _disposableD = new MyDisposable("_disposableD");
public MyDisposable DisposableC
{
get { return _disposableC; }
}
public MyDisposable DisposableD
{
get { return _disposableD; }
}
}
class Program
{
static void Main(string[] args)
{
using(MyBaseClass instance = new MyClass())
{
Console.WriteLine(instance.BaseProtectedDisposableA.Name + " is telling his name...");
Console.WriteLine("--------------------------------------------------------");
}
Console.ReadKey();
}
}
}
そしてそれはこのようなものを印刷します:
_baseProtectedDisposableA is telling his name...
-------------------------------------------------------
_disposableC is disposed
_disposableD is disposed
_baseProtectedDisposableA is disposed
問題は、これをどのように印刷するかです。
_baseProtectedDisposableA is telling his name...
-------------------------------------------------------
_disposableC is disposed
_disposableD is disposed
_baseProtectedDisposableA is disposed
_baseDisposableB is disposed
または、言い換えると、プライベートフィールド_baseDisposableBはどこにあり、どのように破棄するのですか?
ありがとうございました。