Skip to content

Instantly share code, notes, and snippets.

@lukaspj
Created January 9, 2015 19:13
Show Gist options
  • Save lukaspj/71140b54d4d55e041f9b to your computer and use it in GitHub Desktop.
Save lukaspj/71140b54d4d55e041f9b to your computer and use it in GitHub Desktop.
DynamicVariables example
namespace ImplicitInheritance
{
class DerivedSimObject : SimObject
{
public DerivedSimObject(int ID)
: base(ID)
{
}
}
}
using System;
using System.Collections.Generic;
using System.Dynamic;
namespace ImplicitInheritance
{
class DynamicVariables : DynamicObject
{
Dictionary<string, object> OmniDotSelf = new Dictionary<string, object>();
private int mID;
public DynamicVariables(int ID)
{
mID = ID;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
// This can easily be replaced by:
// Omni.self == null ? null : Omni.self.GetVar(_ID.Trim() + "." + binder.Name);
return OmniDotSelf.TryGetValue(binder.Name, out result);
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
OmniDotSelf[binder.Name] = value;
return true;
}
}
}
using System;
namespace ImplicitInheritance
{
class Program
{
static void Main(string[] args)
{
DerivedSimObject sim = (dynamic)new TorqueID(42);
sim.Dynamics.Fish = 2;
Console.WriteLine(sim.Dynamics.Fish + sim.mID);
Console.ReadKey();
}
}
}
using System;
namespace ImplicitInheritance
{
class SimObject
{
public int mID;
public dynamic Dynamics;
public SimObject(int ID)
{
mID = ID;
Dynamics = new DynamicVariables(mID);
}
}
}
using System;
using System.Dynamic;
namespace ImplicitInheritance
{
class TorqueID : DynamicObject
{
private int mID;
public TorqueID(int ID)
{
mID = ID;
}
public override bool TryConvert(ConvertBinder binder, out object result)
{
if (binder.Type.GetConstructor(new Type[] { typeof(int) }) != null)
{
result = Activator.CreateInstance(binder.Type, mID);
return true;
}
result = null;
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment