|
-
Apr 24th, 2006, 10:40 AM
#1
Thread Starter
Hyperactive Member
[RESOLVED] [2.0] follow up question to jmcilhinney...about Type class
Jm,
You gave me an example ...
Code:
Type typ1 = typeof(string);
string str = "Hello World";
Type typ2 = str.GetType();
I understand by getting Type object we can get more details like the methods, member infor, attributes etc..but under what circumstances do we need to know those details??
can you point to me any example code that reads more details of an object using Type??
thanks
nath
-
Apr 24th, 2006, 03:18 PM
#2
Re: [2.0] follow up question to jmcilhinney...about Type class
Here is an example from a project of mine.
This function takes any number of parameters of varying types, and adds text to a Rich Text Box. It needs to find out the type of each object passed in order to decide what action to take -- ie, if it's a string, add it to the text property; if it's a color/font, change the currently selected color/font respectively.
Code:
public void WriteTextF(params object[] objs)
{
Type type;
Color color = Color.White;
Font font = new Font("Courier New",8.25f);
for(int i = 0; i < objs.Length; i++)
{
type = objs[i].GetType();
if (type == typeof(string))
{
// write text to textbox
RTB.SelectionStart = RTB.Text.Length;
RTB.SelectionLength = 0;
RTB.SelectionFont = font;
RTB.SelectionColor = color;
RTB.SelectedText = (string)(objs[i]);
RTB.SelectionStart = RTB.Text.Length;
}
//update color choice
else if (type == typeof(Color))
{
color = (Color)(objs[i]);
}
//update font choice
else if (type == typeof(Font))
{
font = (Font)(objs[i]);
}
// bad type! bad!
else
{
//throw new Exception("Unsupported Type");
}
}
The main concept is that the GetType() function is virtual -- ie, if I have a class "base," and a class "derived" which is derived from base, and I do something like the following:
Code:
derived d = new derived();
base b = d;
Console.WriteLine(b.GetType().ToString());
The output would tell me that 'b' is actually a derived object.
Hope this helps.
Every passing hour brings the Solar System forty-three thousand miles closer to Globular Cluster M13 in Hercules -- and still there are some misfits who insist that there is no such thing as progress.
-
Apr 24th, 2006, 05:36 PM
#3
Re: [2.0] follow up question to jmcilhinney...about Type class
There are also existing properties and methods in the Framework that use the Type class, for instance the DataType property of the DataColumn class, which indicates what type of data the column can contain.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|