Contract.cs
public class Contract
{
public string Name { get; set; }
public string Status { get; set; }
public Asset[] Asset { get; set; }
public Group[] Group { get; set; }
public Contract( string name, string status ){
Name = name;
Status = status
Asset = new Asset[ 10 ];
Group = new Group[ 10 ];
}
}
public class Asset {
public int ID { get;set;}
public string Value {get;set;}
}
public class Group{
public int ID { get;set;}
public string Value {get;set;}
}
Thats the basic structure of my Contract, here is the client code:
static void Main( string[] args )
{
Contract c = new Contract( "TestContract", "Default" );
for( int i = 0; i < 10; i++ )
{
c.Asset[ i ] = new Asset( i*10, "base" );
c.Group[ i ] = new Group( i*100, "newGroup" );
}
Console.WriteLine( c );
updateContract( c, "Asset", 0, "Value", ".666." );
updateContract( c, "Group", 0, "Value", ".999." );
updateContract( c, "Group", 2, "Value", ".999." );
updateContract( c, "Status", "Awesome" );
Console.WriteLine( c );
}
public static void updateContract( Contract contract, string collection, int index, string property, string value )
{
object collectionObject;
if( collection == "Asset" )
{
collectionObject = contract.Assets[ index ];
}
else if( collection == "Group" )
{
collectionObject = contract.Group[ index ];
}
else
{
throw new Exception( "Couldn't parse " + collection + " properly" );
}
SetPropValue( collectionObject, property, value );
}
public static void updateContract( Contract contract, string Property, string value )
{
SetPropValue( contract, Property, value );
}
private static void SetPropValue( object src, string propName, string value )
{
PropertyInfo pi = src.GetType().GetProperty( propName );
//Gets the type of the property passed in
Type t = pi.PropertyType;
//Converts the string to the property type
object newVal = Convert.ChangeType( value, t );
//Sets the newly typed object to the property
pi.SetValue( src, newVal, BindingFlags.SetProperty, null, null, null );
//pi.SetValue( src, newVal); // In .NET 4.5
}
Basically I want to remove that if/else block and put something like this in
Quote
object[] objectCollections = (object[]) GetPropValue(contract, collection);
object curCollectionObject = objectCollections[index];
SetPropValue(ref curCollectionObject, property, value);
object curCollectionObject = objectCollections[index];
SetPropValue(ref curCollectionObject, property, value);
But thats breaking. Any ideas or help would be greatly appreciated. Sorry for the long post
This post has been edited by SwiftStriker00: 04 December 2012 - 09:26 AM

New Topic/Question
Reply



MultiQuote



|