runtime casting

M

Marco

I can't convert data to runtime.


class User
{

public User(string first,string last)
{
this.first=first;
this.last=last;
}

public string first;
public string last;

}

class Environment
public IDictionary dict;

public Environment()
{
dict=new Hashtable();
}

public void bind(String name,Object data)
{
Object d=data;
dict.Add(name,d);
}
}

class Template
{
String Query; // Query is "repeat(people) people.first..."

public String gen(Environment env)
{
Object data=env.dict["people"]
// ....

}

}

Main()
{

user[] users=new User{
new User("Jack", "Forester")
new User("Tony", "Corallo")
}

Template tab=Template.parse("repeat(people) people.first...")
Environment env=new Environment();
env.bind("people",users);
String table=tab.gen(env);

}


The purpose is realize a template engine.

My input is :
"repeat(people) people.first..."

My output must be :

Jack
Tony


The method env.bind() can take a generic collection.
In the method gen of template class I have to read and print all
attribute of generic collection.
For example:
in this case I have to read "users" and print the "first" attribute of
all user element.
The gen output must be.

Jack
Tony

My problem is:

After:
Object data=env.dict["people"]
how can I convert data to user[].
I have to do this at runtime.


I can't do user[] User=(user[]) data;

because the collection is generic and I don't know the type.

How can I use reflection to do it?
 
M

Mrinal Kamboj

just a set of suggestions , if understood your question correctly :

Instead of trying reflection can't you try using "is" operator on object
data , i am not very sure , but i think it can be used at runtime for a
limited number of types that may be contained in data type , you can
check if(data is users[]) or somethin else works for you .

or i think "as" operator can be another handy thing , but in all these
cases there should be finite number of classes that you should code .

Mrinal
 
I

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

Hi,

Try this:
foreach( FieldInfo field in data.GetType().GetFields()
Console.Write ( field.GetValue( data ).ToString() );


Yopu can check for the member type, or any other thing you need, but that is
the core of it.




Cheers,
 
M

Marco

Don't work.
It work if "data" is a user class, but don't work in this case because
data is a array of user.
 
I

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

Hi,

Well, wrap it in another foreach:

foreach( object o in data ) //
foreach( FieldInfo field in o.GetType().GetFields()
Console.Write ( field.GetValue( data ).ToString() );

then you will get all the properties of all the elements of the collection


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