This repository has been archived by the owner on Jun 11, 2021. It is now read-only.
forked from dotnet/dotNext
/
Disposable.cs
59 lines (54 loc) · 2.24 KB
/
Disposable.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using static System.Linq.Expressions.Expression;
namespace DotNext
{
using Reflection;
using ConceptAttribute = Runtime.CompilerServices.ConceptAttribute;
/// <summary>
/// Represents dispose pattern as a concept.
/// </summary>
/// <remarks>
/// This concept provides access to Dispose method of type <typeparamref name="T"/> even
/// if it doesn't implement <see cref="IDisposable"/> interface directly.
/// </remarks>
/// <typeparam name="T">A type which implements dispose pattern.</typeparam>
/// <seealso href="https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose">Implementing Dispose method</seealso>
[Concept]
#if NETSTANDARD2_1
public static class Disposable<T>
#else
public static class Disposable<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] T>
#endif
{
private delegate void DisposeMethod(in T instance);
private static readonly DisposeMethod DisposeMethodImpl;
static Disposable()
{
var disposeMethod = typeof(T).GetDisposeMethod();
if (disposeMethod?.DeclaringType is not null && disposeMethod.ReturnType == typeof(void))
{
if (disposeMethod.DeclaringType.IsValueType)
{
Disposable<T>.DisposeMethodImpl = disposeMethod.CreateDelegate<DisposeMethod>();
}
else
{
var instance = Parameter(typeof(T).MakeByRefType(), "this");
Disposable<T>.DisposeMethodImpl = Lambda<DisposeMethod>(Call(instance, disposeMethod), instance).Compile();
}
}
else
{
throw new MissingMethodException(typeof(T), nameof(IDisposable.Dispose), typeof(void), Array.Empty<Type>());
}
}
/// <summary>
/// Disposes specified object.
/// </summary>
/// <param name="obj">An object to dispose passed by reference.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Dispose(in T obj) => DisposeMethodImpl(in obj);
}
}