quentinA
asked on
Help with c# reflection?
I am trying to write a WPF custom control, and am trying to refactor it so that any List<T> can be converted into a List<CustomType>.
The CustomType has an Id property that I want to be assigned with the value of the Id property from an instance of the source T.
But my problem is how to map the name of the Id property on the source to the Id property on the CustomType.
A pseudocode method follows:
private void UsePropertiesOfInputCollec tionInColl ectionOfAn otherClass (IEnumerab le<object> inputCollection , string nameOfTheMemberThatHoldsTh eIdValueOf AnInputObj ect, Type typeOfTheObjectsInTheColle ction)
{
foreach (var inputObject in inputCollection)
{
//cast the input object to the typeOfTheObjectsInTheColle ction
//interogate the member on the (cast)inputObject that is named: nameOfTheMemberThatHoldsTh eIdValueOf AnInputObj ect
//Create a new instance of the AnotherClass
//assign the value of the interogated member to a property called AnotherClass.ClassID
}
}
Can you help?
The CustomType has an Id property that I want to be assigned with the value of the Id property from an instance of the source T.
But my problem is how to map the name of the Id property on the source to the Id property on the CustomType.
A pseudocode method follows:
private void UsePropertiesOfInputCollec
{
foreach (var inputObject in inputCollection)
{
//cast the input object to the typeOfTheObjectsInTheColle
//interogate the member on the (cast)inputObject that is named: nameOfTheMemberThatHoldsTh
//Create a new instance of the AnotherClass
//assign the value of the interogated member to a property called AnotherClass.ClassID
}
}
Can you help?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
It isn't a school assignment (although I often feel as though I am at school, because i'm teaching myself).
I had done following (which works), I'll try yours too.
var starterObjectType = starterCollection.First().
foreach (var starterObject in starterCollection)
{
//cast the input object to the typeOfTheObjectsInTheColle
MethodInfo castMethod = this.GetType().GetMethod("
object castedObject = castMethod.Invoke(null, new object[] { starterObject });
//interogate the member on the (cast)inputObject that is named: nameOfTheMemberThatHoldsTh
var idResult = GetPropValue(castedObject,
var iiid = Guid.Parse(idResult);
//assign the value of the interogated member to a property called AnotherClass.ClassID
RecordStarterProperties.Ad
}