Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Get all property name-value pairs from one class; pass to another...

Status
Not open for further replies.

phobe62

Programmer
Jan 30, 2004
22
US
I have several classes that are going to dump their properties to a "mother ship" class. In trying to accomplish this, I'm using a foreach loop, like this:

------------------------------
public void MoveForward(System.Type t)
{
foreach (PropertyInfo propertyInfo in t.GetProperties())
{
// Set the property with this same name in another class to the value of the property in the class t
}
...
------------------------------

So... Does anybody know how it can be done?
 
I don't know the context in which you need to do:
>foreach (PropertyInfo propertyInfo in t.GetProperties())
{
// Set the property with this same name in another class to the value of the property in the class t
}

In the propertyInfo object you cannot change the NAME of the property.
Everything is readonly excepting the value of the property.
Example:
public MyClass {
private double _pTax=0.075;
public double TPS
{
get {return _pTax;}
set {_pTax = value;}
}
}
MyClass MyObj = new MyClass();
Type MyType = Type.GetType("MyObj");
PropertyInfo propertyInfo = MyType.GetProperty("TPS");
propertyInfo.SetValue( MyObj, 0.065, null);
The value of _pTax is now 0.065 but you cannot change its "TPS" accessor name.

-obislavu-

 
Play" with the GetValue and SetValue methods. As long as the properties are not indexed and the types do not change between classes you should be OK.
Here is a "worst case" using fieldInfo, involving TypeChange

objTypecodeTo = System.Type.GetTypeCode(fldInfoTo(I).FieldType)
If Not (fldInfoFrom(I).GetValue(objFrom) Is Nothing) Then
Try
fldInfoTo(I).SetValue(objTo, _
System.Convert.ChangeType( _
fldInfoFrom(I).GetValue(objFrom), _
objTypecodeTo))
Catch ex As Exception
K += 1
strErrors(K) = strFldName & ": does not convert to Type=" & _
objTypecodeTo.ToString
End Try
End If

Forms/Controls Resizing/Tabbing
Compare Code
Generate Sort Class in VB
Check To MS)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top