DisposeHelper
using System;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace NUnit.Framework.Internal
{
[System.Runtime.CompilerServices.NullableContext(1)]
[System.Runtime.CompilerServices.Nullable(0)]
internal static class DisposeHelper
{
public static bool IsDisposable(Type type)
{
if (typeof(IDisposable).IsAssignableFrom(type))
return true;
MethodInfo method;
return TryGetAsyncDispose(type, out method);
}
[System.Runtime.CompilerServices.NullableContext(2)]
public static void EnsureDisposed(object value)
{
if (value != null) {
if (TryGetAsyncDispose(value.GetType(), out MethodInfo method))
AsyncToSyncAdapter.Await(null, () => method.Invoke(value, null));
else
(value as IDisposable)?.Dispose();
}
}
private static bool TryGetAsyncDispose(Type type, [System.Runtime.CompilerServices.Nullable(2)] [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out MethodInfo method)
{
method = null;
Type interface = type.GetInterface("System.IAsyncDisposable");
if ((object)interface == null)
return false;
method = interface.GetMethod("DisposeAsync", Type.EmptyTypes);
return (object)method != null;
}
}
}