I try to extract fields or properties from a dynamic class using reflection, but when I call a dynamic object using Getfield or GetProperty, it will never be able to find this field and none of the dynamic methods object.Try * will be entered.
Not sure why this is not working on .net4.
See below for the dynamic testdyn test class.
I call it this way:
dynamic td = new testdyn(); td.SendDebugEvent += new DebugDelegate(debug); td.test();
Getting these results:
one = -1 two = -1 fiddle = -1 test = -1 set: fiddle = 241827974 fiddle = -1
Expect to see
one = 1 two = 2 fiddle = 3 test = -1 set: fiddle = 241827974 fiddle = 241827974
What am I doing wrong?
NOTE: it works if I call 'td.fiddle' ... but it seems strange that you would not know the name to create the class, but you would know it to access it?
from this post it seems that maybe reflection is not supported for dynamicobject, as it implements idynamicmetaobjectprovider
How can I reflect the elements of a dynamic object?
The problem is that this code is used by an external application that uses reflection.
let me know if you have any ideas.
.
public delegate void DebugDelegate(string msg); public class testdyn : System.Dynamic.DynamicObject { List<string> items = new List<string>(new string[] { "one", "two", "fiddle", "my", "lou" }); List<int> vals = new List<int>( new int[] { 1,2,3,5,8 }); public event DebugDelegate SendDebugEvent; void debug(string msg) { if (SendDebugEvent!=null) SendDebugEvent(msg); } public void set(string name, int v) { var idx = items.IndexOf(name); if (idx < 0) return; vals[idx] = v; debug("set: " + name + " = " + v); } int get(string name) { object o = null; var t = GetType(); try { o = t.GetProperty(name).GetValue(this, null); int v = (int)o; return v; } catch { try { var f = t.GetField(name); o = f.GetValue(this); return (int)o; } catch { } } return -1; } string g(string name) { return name+" = "+get(name).ToString(); } Random r = new Random(); public void test() { test(string.Empty); } public void test(string mytmp) { var t = GetType();