Reflection, how to?

J

James B

If I have a Class below and I want to use Reflection to get classes
member variable value how should I actually do it? Can anyone help?

Cheers!

using System;
using System.Reflection;

namespace ConsoleApplication1
{
/// <summary>
/// Summary description for Class.
/// </summary>
class MyClass
{
private string MyValue = String.Empty;
public void setMyValue(string s)
{
MyValue = s;
}

[STAThread]
static void Main(string[] args)
{
MyClass o = new MyClass();
o.setMyValue("Value is String");

// How to get varaible MyValu's value
// using Reflection????
}
}
}
 
M

Michael Nemtsev

Hello James,

See msdn sample http://msdn2.microsoft.com/en-us/library/ch9714z3.aspx

JB> If I have a Class below and I want to use Reflection to get classes
JB> member variable value how should I actually do it? Can anyone help?
JB>
JB> Cheers!
JB>
JB> using System;
JB> using System.Reflection;
JB> namespace ConsoleApplication1
JB> {
JB> /// <summary>
JB> /// Summary description for Class.
JB> /// </summary>
JB> class MyClass
JB> {
JB> private string MyValue = String.Empty;
JB> public void setMyValue(string s)
JB> {
JB> MyValue = s;
JB> }
JB> [STAThread]
JB> static void Main(string[] args)
JB> {
JB> MyClass o = new MyClass();
JB> o.setMyValue("Value is String");
JB> // How to get varaible MyValu's value
JB> // using Reflection????
JB> }
JB> }
JB> }
---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsche
 
G

Guest

I m explaining it below

Below is data of my assembly

string ModuleName = "TestAssembly.dll";
string TypeName = "TestClass";
string MethodName = "TestMethod";


Loading my assembly using
Assembly myAssembly = Assembly.LoadFrom(ModuleName);


After that three loops are used to inspect the assembly and get the chosen
module/type/method combination. Within the last loop the type is instanciated
and the method is called. The method can be called with parameters, but here
we
choose <I>null </I>for methods with no parameters. There can also be a
response
from the method, which we put into a general object.</P><PRE lang=cs>Module
[] myModules = myAssembly.GetModules();
foreach (Module Mo in myModules)
{
if (Mo.Name == ModuleName)
{
Type[] myTypes = Mo.GetTypes();
foreach (Type Ty in myTypes)
{
if (Ty.Name == TypeName)
{
MethodInfo[] myMethodInfo = Ty.GetMethods(flags);
foreach(MethodInfo Mi in myMethodInfo)
{
if (Mi.Name == MethodName)
{
Object obj = Activator.CreateInstance(Ty);
Object response = Mi.Invoke(obj, null);
}
}
}
}
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top