Feedback

C# - PrivateAccess

Veröffentlicht von am 11/4/2015
(0 Bewertungen)
Wrapper für den Zugriff auf private Felder und Methoden über dynamic.

Sinnvoll für UnitTests

Beispiel:


public class TestClass
{
private int _field1 = 0;

private int GetField()
{
return _field1;
}

private void IncField()
{
_field1++;
}
}


static void Main(string[] args)
{

var test = new TestClass();
dynamic priv = new PrivateAccess(test);

int i = priv.GetField();
Console.WriteLine(i);

priv.IncField();

priv._field1++;

i = priv._field1;
Console.WriteLine(i);

Console.ReadLine();
}

    public class PrivateAccess : DynamicObject
    {
        private readonly object _nested = null;
        public PrivateAccess(object obj)
        {
            _nested = obj;
        }

        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            result = null;

            var methods = _nested.GetType().GetMethods(BindingFlags.Instance | BindingFlags.NonPublic);
            var method = methods.FirstOrDefault(m => m.Name == binder.Name && m.GetParameters().Count() == binder.CallInfo.ArgumentCount);
            if (method == null)
            {
                return false;
            }

            result = method.Invoke(_nested, args);
            return true;
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            result = null;

            var field = _nested.GetType().GetField(binder.Name, BindingFlags.Instance | BindingFlags.NonPublic);
            if (field == null)
            {
                return false;
            }

            result = field.GetValue(_nested);
            return true;
        }

        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            var field = _nested.GetType().GetField(binder.Name, BindingFlags.Instance | BindingFlags.NonPublic);
            if (field == null)
            {
                return false;
            }

            field.SetValue(_nested, value);
            return true;
        }
    }
Abgelegt unter privateaccess, reflection, dynamic.

Kommentare zum Snippet

 

Logge dich ein, um hier zu kommentieren!