Reflection - Need advice

C

Cralis

Hi guys,

Someone once said, 'You can do that with reflection'. I can't recall
what it was I was trying to do at the time, but then he said, 'Any
developer knows what reflection is...'. I kept quiet and smiled.

What is reflection!?

I have been reading it up, and all I can work out is that it has
something to do with Late Binding, and the use of GetType and Type.
But I can't for the life of me figure out why I would want to use it.
Why would I declare something of type Object? Surely I should know
what I wanrt when I write the code?

Hope someone can shed light on it for me, as I'm sure it's an
important thing to know about.

Thanks guys.
 
C

Cralis

Thanks Pete!
Nice answer.
I'm battling to understand this bit:
As for what it is, it's basically anything in the framework that is
"reflective" or "introspective". That is, it refers to the program
itself, as opposed to other kinds of data. Most of the classes can be
found in the System.Reflection namespace.

Something that refers to the program it's self.
Something like.. getting the name of the currently used executable? Is
that a good example of what you mean? I can't think of many other
'refelective' things.
An example of something that might use reflection would be data binding.
Many .NET GUI controls, for example, allow you to provide an object
reference, and then one or more names of properties on the object to be
used for things like text to be used in the GUI, a value to be returned to
code, etc.

I have an object (for example) called oUser. I actually have a
List<oUser> lstUser. I then do a foreach(oUser user in lstUser) and
populate a DropDown box with ddUser.Items.Add(new ListItem
(user.username, user.id.tostring()))

From your above statement, that's what I am thinking (Using an object
to populate a GUI control), but I think I am wrong. Way off. :)
However, what you write below indicates that it's happening behind the
scene:
That's hardly the only use, but it might be one of the most common people
would run into. Note, though, that to use data binding you don't actually
have to write code that uses the reflection features. But reflection is
going on behind the scenes.

Can you maybe help me understand that a bit better?

Again, thanks,
Craig
 
P

Peter Morris

Hi Cralis
I kept quiet and smiled.

I always ask, no matter how stupid I suspect I might look as a consequence.
It's a good way to learn new stuff, actually increases your confidence in
your ability, and quickly shows up the other guy as a fraud if he doesn't
know the subject well enough to explain it properly :)

What is reflection!?

public class Person
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}

private void DoSomething(string x)
{
}
}


Using reflection on the assembly you can get a list of Type. Using that
Type you can get a list of constructors, methods, properties, method's
parameters etc. You can then use those references to do stuff like invoke
the methods and so on.

I used reflection recently when I had to send a text-based command to
objects implementing ISignalTarget.

public interface ISignalTarget
{
void AcceptSignal(ISignal signal);
}

I created a base class which automatically dispatched the signal to an
appropriately named method, so if signal.ID was "Copy" I would look for

(any exposure) void Accept_CopySignal(CopySignal signal)
{
}

and if found I would invoke it.

When you add .NET attributes to your code I believe reflection is used to
discover those.

In summary, reflection is possible because .NET understands how to read the
contents of the assembly. As a consequence you are able to read those
contents yourself, and also execute methods etc too (MethodInfo.Invoke).

One last example. If you have assemblies in a "Plugins" folder of your app
that you want loaded dynamically, maybe because other people are allowed to
write their own (like you can with Photoshop). You could load each of the
assemblies in the Plugins folder, then get all types in the assembly that
implement IMyPlugin. If that type is also decorated with your own
PluginAttribute you could

01: Read PluginAttribute.DisplayName and MenuLocation to display the plugin
in the menu.
02: When the user clicks the menu you can create an instance of the plugin
and execute it.


The new ASP MVC framework uses reflection to take a url like this

http://localhost/Employee/View/1

and execute a method like this

public class EmployeeController : .........
{
public ActionResult View(int id) { ....... }
}


I tried to think of as many examples as possible in the hope you could
identify with one :)

Pete
====
http://mrpmorris.blogspot.com
http://www.capableobjects.com
 
J

Jeff Johnson

Something that refers to the program it's self.
Something like.. getting the name of the currently used executable? Is
that a good example of what you mean? I can't think of many other
'refelective' things.

Have you ever used the Object Browser in the IDE? That's pretty much the
poster child for Reflection. The Object Browser basically says, "Okay,
here's a list of .EXEs and .DLLs. I'm going to dig into them and see what
they contain." That's Reflection, mostly.

The few times I have used Reflection (other than when I wrote my own Object
Browser for the purpose of LEARNING about Reflection) have mainly centered
around instantiating objects at run-time (basically its "other" function).
In other words, I wrote a program that was to be "extensible" in that it
could create objects of types that were unknown (and probably not even
written) when I compiled the original program. I store the fully-qualified
name of these objects in a database and then my program reads this data and
creates them as needed when it's running.
 
I

Ignacio Machin ( .NET/ C# MVP )

I have an object (for example) called oUser. I actually have a
List<oUser> lstUser. I then do a foreach(oUser user in lstUser) and
populate a DropDown box with ddUser.Items.Add(new ListItem
(user.username, user.id.tostring()))


But what if you do not know the type the list is holding. You receive
a List<T> , all you know is that T implements a property named Text
and also has another named Id.
Under this case you can still create your Items elements. By using
reflection you can extract the values of those properties.
Can you maybe help me understand that a bit better?

In the example above you have that explanation. DropDown has no idea
of the types that the collection holds, all it knows is the name of
the property used for Text & Value.
BTW, your code can be rewritten like:

dropDown.DataSource = lstUser
dropDown.DataTextField = "username";
dropDown.DataValueField = "Id";
dropDown.DataBind();

Notice that I do not have to convert Id to string as you had to do in
your code. All I especify is the name of the properties the dropdown
has to look for.
Also note that the list can has different types, if you have these
classes:

class Employee{
public Username{get;set;}
pubic Id{get;set;}
}
and
class Client{
public Username{get;set;}
pubic Id{get;set;}
}

you can mix them in a list and bind it to the above dropdown with no
issue at all
 

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