Dotnet Private Accessor

Overview

Sample Class

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public class MyClass
{

    private string MyMethod()
    {
        return "myMethodResult";
    }
    private string _myfield

    private string Property {get; 
    set;}
    
}

Reflection

1
2
var value = typeof(MyClass).GetMethod("MyMethod", BindingFlags.Instance | BindingFlags.NonPublic)!
    .Invoke(sut, Array.Empty<object>());

Core 8 Improvement

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13

// Wrapper Class
public class Wrapper
{
    [UnsafeAccessor(UnsafeAccessorKind.Method, Name="MyMethod")]
    public static extern string GetMyMethod(MyClass myclass);

    [UnsafeAccessor(UnsafeAccessorKind.Fied, Name="_myField")]
    public static extern string GetMyField(MyClass myclass);

    [UnsafeAccessor(UnsafeAccessorKind.Property, Name="getMyProperty")]
    public static extern string GetMyProperty(MyClass myclass);
}