Hi,
I'm trying to do something with reflection that's a little wierd. The idea
is that I call for a field to be updated on a base class. Using reflection
it first updates the value, and then updates the change that has been made
to a dictionary. The code below is just to encourage some ideas, if you look
at most of the code you find that most of it is pretty pointless. I might as
well have Translate(string fieldname, ref string objecttotranslate) as the
method and call the fielddictionary directly.
What I'm really looking to do though, is to get rid of the 'string
fieldname' and simplify the method so that it is simply 'Translate(ref
string field)'
The problem is that I can seem to find anyway to get the field 'ref string
field' is refering to, and even if I could I'm not sure how I could use
reflection to then get the name of the field that was passed by reference. I
suppose one solution would be to iterate through Type.GetFields() and
compare values, but does anyone know of a better solution?
Thanks and kind regards
James
using System;
using System.Reflection;
using System.Collections.Specialized;
using System.Diagnostics;
public class BaseClass
{
private HybridDictionary fielddictionary = new HybridDictionary();
public BaseClass()
{
FieldInfo fi =
this.GetType().GetField("helloworld",
BindingFlags.NonPublic | BindingFlags.Instance);
fielddictionary.Add(fi.Name, fi.GetValue(this));
}
protected void Translate(FieldInfo fieldinfo)
{
this.Translate(fieldinfo.FieldHandle);
}
protected void Translate(RuntimeFieldHandle handle)
{
FieldInfo fi = FieldInfo.GetFieldFromHandle(handle);
fi.SetValue(this, "Hola Mundo");
fielddictionary[fi.Name] = "Hola Mundo";
}
}
public class SubClass :BaseClass
{
private string helloworld = "Hello World";
internal string HelloWorld{get{return helloworld;}}
public SubClass(){}
internal void Translate()
{
// RuntimeFieldHandle handle =
// this.GetType().GetField("helloworld",
// BindingFlags.NonPublic |
BindingFlags.Instance).FieldHandle;
// base.Translate(handle);
FieldInfo fieldinfo = this.GetType().GetField("helloworld",
BindingFlags.NonPublic | BindingFlags.Instance);
base.Translate(fieldinfo);
}
}
public class Test
{
public static int Main()
{
SubClass test = new SubClass();
Debug.WriteLine(test.HelloWorld);
test.Translate();
Debug.WriteLine(test.HelloWorld);
return 0;
}
}