Questions about refelection

T

Thomas

Hello,

I'm programming a program, where I don't know which objects are needed. So I
want to use the mechanism of reflection.

I can create the objects I need by reflection, but there are some questions
I don't have a solution. Perhaps anybody can help?

First i want to write a little code down here, the code isn't so important
but it describes the structure of my classes.
Code:
public interface ITest
{
void Find(string keyword);
}

public class CTest : ITest
{
string index;
void Find(string text)
{}
public CTest()
{}
}

public class CSolute
{
protected ITest testclass;
protected string text;
public ITest Index
{
get{return testclass;}
}
public string Text
{
get{return text;}
set{text=value;}
}
public CSolute()
{}
}

The class CSolute is saved in an arraylist and all fields are filled (the
fields of the class CTest are filled, too)
I've managed to get an object of the class CSolute

And now my problems:
1. I want to display the classname of CSolute.testclass (not the name of the
interface!). How can I manage this?
2. How can I get the object of the class CSolute.testclass by reflection?
3. How can I invoke the method CTest.Find by reflection?

I would be glad if anyone of you have an answer.

cu Thomas
 
M

Mattias Sjögren

Thomas,
public class CTest : ITest
{
string index;
void Find(string text)
{}

Find must be public for your code to compile.

2. How can I get the object of the class CSolute.testclass by reflection?

The easiest way would be to use the Index property.

object test =
soluteObj.GetType().GetProperty("Index").GetValue(soluteObj, null);

1. I want to display the classname of CSolute.testclass (not the name of the
interface!). How can I manage this?
test.GetType().Name


3. How can I invoke the method CTest.Find by reflection?

test.GetType().GetMethod("Find").Invoke(test, new object[] {"abc"});



Mattias
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi Thomas,
And now my problems:
1. I want to display the classname of CSolute.testclass (not the name of the
interface!). How can I manage this?

object o = csolute_Instance.Index.GetType().FullName
this will give you the name including the namespace of the type returned.
2. How can I get the object of the class CSolute.testclass by reflection?
What yo mean with this ? you get the object just calling the property, it's
only that you see the "ITest" part of it. you can always cast it to the type
if you know what type it is.

3. How can I invoke the method CTest.Find by reflection?
Why using reflection for this? just use the interface as declared


Cheers,
 

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