简体   繁体   中英

dynamic type casting of objects in C#.net

I have created a class student and in that class contact object is created (aggregation). I am retrieving all stored objects in "object" array.

If I want to access student attribute I have to type cast it with student and if I want to access contact attribute either I have to give full path ( student_object.contact_object.attribute_name ) or simply type cast with contact and get the attribute value.

I have stuck at two places:

  1. If I accept class name from user and then want to access the value. How can I do that? How to type cast with textbox variable.
  2. If field name I accept from user in text box . How can I access the value using text box variable?

Jon, Actually I have created a object oriented database in C#.NET. where above classes are there. I am Retrieving all objects in Object array. Class student has field name and age , while contact has mobileID . Now I am creating a query through textboxes. If user want to see name of all the object , then var2 name he shold put. but i am not able to get this message messageBox.show(o0 as Student).var2); Same if instead of Student if I give var1 messageBox.show(o0 as var1).var2); Can I do this? thanks/Bharti

Casting is important for compile-time information. That precludes anything that the user provides at execution time .

It sounds like you really need to just reflection:

PropertyInfo property = value.GetType().GetProperty(propertyName);
// Insert validation here...
object propertyValue = property.GetValue(value, null);

You'll need to be smarter if you want the user to be able to evaluate a path of properties such as Address.ZipCode but it should give you a starting point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM