开发者

dynamic type casting

开发者 https://www.devze.com 2023-03-07 13:10 出处:网络
Now I think it is clear. I have created a object oriented database in C#.NET where two classes are there. Student and contacts. Contacts are inside student. I am Retrieving all objects in Object array

Now I think it is clear. I have created a object oriented database in C#.NET where two classes are there. Student and contacts. Contacts are inside student. I am Retrieving all objects in Object array. Class student has fields name and age, while contact has mobileID.

Now I am creating a query through textboxes. Created textboxes. one for select and one for from. in from(var1) class name is accepted , whil开发者_StackOverflow社区e in select(var2), field name is accepted. If user want to see name of all the objects, then var2 "name" should be input; but I am not able to get this message

messageBox.show(obj[0] as Student).var2);

it is giving error var2 , 'object' does not contain a definition for 'var2' and no extension method 'var2' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

Same issue if instead of Student if I give var1 messageBox.show(obj[0] as var1).var2);

Can I do this?


You can't do this without using reflection.

var2 is a variable containing the name of a property. You can't just say obj.var2 and get the value of the property whose name is in var2.

You'd have to do something like this:

var objType = obj[0].GetType();
var propInfo = objType.GetProperty(var2);
var value = propInfo.GetValue(obj[0], null);


Your syntax looks strange, the number of closing parenthesis doesn't match the opening. Maybe:

MessageBox.show((obj[0] as Student).var2);

Also make sure that this va2 property is public inside the Student class:

public string var2 { get; set; }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号