Quantcast
Channel: ClearScript
Viewing all articles
Browse latest Browse all 2297

New Post: Cannot get property of a derived class

0
0
Hi ravetam!

Great question. This may be an example of ClearScript behaving a little too much like C# :)

The expression you're evaluating, e.Location.Point, doesn't compile in C#, and it doesn't work in script code for the same reason. You need to cast e.Location to LocationPoint.

Here's how to do the cast in script code:
engine.AddHostObject("host", new HostFunctions());
engine.AddHostType("LocationPoint", typeof(LocationPoint));

engine.AddHostObject("e", e);
Console.WriteLine(engine.Evaluate("host.cast(LocationPoint, e.Location).Point"));
If you're wondering why ClearScript exposes the declared type of the property instead of the runtime type of its value, it has to do with preserving static type information in order to provide C#-like method binding. Without this behavior, some things might be easier to do in script code, but you'd lose the ability to access .NET members in many scenarios. Your proposed fix, for example, breaks 47 ClearScript tests :)

Nevertheless, ClearScript does provide a way to override its default behavior:
publicclass Element
{
    [ScriptMember(ScriptMemberFlags.ExposeRuntimeType)]
    public Location Location { get; set; }
}
With the Element class defined this way, no cast is necessary in script code.

Thanks, and good luck!

Viewing all articles
Browse latest Browse all 2297

Latest Images

Trending Articles





Latest Images