access private fields of base class

Nov 29, 2013 at 3:33 PM
Is it possible to get & set private fields of base class. Currently unable to get the fields of base class even after casting the object to base. But able to get private fields of derived class using the HostFlag privateaccess.
Coordinator
Nov 29, 2013 at 5:14 PM
Greetings jnair, and thanks for your question!

Unfortunately ClearScript doesn't have a complete solution for private member access. As you've discovered, PrivateAccess only goes so far, and casting doesn't propagate it.

Here's one thing you can do. Let's say your classes look like this:
public class FooBase {
    private int PrivateBaseField;
}
public class Foo : FooBase {
    private string PrivateField;
}
You can expose the base portion of your object separately, with its own PrivateAccess flag:
var foo = new Foo();
engine.AddHostObject("foo", HostItemFlags.PrivateAccess, foo);
engine.AddRestrictedHostObject("fooBase", HostItemFlags.PrivateAccess, (FooBase)foo);
engine.Execute(@"
    foo.PrivateField = 'bar';
    fooBase.PrivateBaseField = 123;
");
It's a bit ugly, but it works :)

Cheers!