casting - cast dynamic object in other type .net -
.net 4 introduced dynamic objects can assign proprieties @ run time. have dynamic object , need cast in type. following code snippet
public class eobject : dynamicobject { dictionary<string, object> m_dictfields = new dictionary<string, object>(); private string m_strname; public string name { { return m_strname; } set { m_strname = value; } } public override bool trygetmember(getmemberbinder binder, out object result) { if (m_dictfields.containskey(binder.name)) { result = m_dictfields[binder.name]; return true; } else { return base.trygetmember(binder, out result); } } public override bool trysetmember(setmemberbinder binder, object value) { if (!m_dictfields.containskey(binder.name)) m_dictfields.add(binder.name, value); else m_dictfields[binder.name] = value; return true; } } // assigning properties dynamic object static void main(string[] args) { dynamic organization = new eobject(); organization.name = "test org name"; organization.modifiedon = datetime.now; organization.createdon = datetime.now; organization.modifiedby = "test modified by"; oganization.createdby = "test user"; // have done eobject neworg = organization eobject; console.writeline("org name: " +organization.name); // working console.writeline("org name: " +neworg.name); // not working }
i getting neworg object fields have added dynamically not accessible me. thanks
when compiler generates code expression organization.name
detects type of variable organization
being dynamic
. decides postpone 'binding' process execution time, because not know object behind variable organization
have name
or modifiedon
properties. methods trygetmember
, trysetmember
called during execution time whenever dynamic object won't have corresponding member. in example trygetmember
, trysetmember
wont called property name, because statically declared on eobject
, called rest of member access defined.
when cast variable eobject
in neworg, compiler static analisis, can see neworg references object name
property, no modifiedon
property, in particular neworg.name
work (i don't know why doesn't), neworg.modifiedon
won't pass compiler verification, issuing following error:
'eobject' not contain definition 'modifiedby' , no extension method 'modifiedby' accepting first argument of type 'eobject' found (are missing using directive or assembly reference?)
Comments
Post a Comment