Quindi ho un codice che imposta una proprietà su un oggetto. Questo codice proviene da una classe di convalida interna che stiamo usando nei test unitari. Qualcosa di così il codice può essere fornito comeCome utilizzare un'espressione <Func> per impostare una proprietà nidificata?
private static void SetDeepValue(object targetObject, Expression<Func<string>> propertyToSet, object valueToSet)
{
var underlyingProperty = ((PropertyInfo)((MemberExpression)propertyToSet.Body).Member);
underlyingProperty.SetValue(targetObject, valueToSet);
}
Questo codice viene utilizzato in un ambiente di tipo unit-test, dove possiamo quindi effettuare chiamate come
foreach (string currentTestCaseValue in TestCaseSets)
{
BusinessObject myCustomer = new BusinessObject();
SetDeepValue(myCustomer,()=>myCustomer.FirstName,currentTestCaseValue);
ValidateBusinessRules(myCustomer);
}
(codice semplificato per brevità/complessità)
Tuttavia, ora, a causa di alcuni refactoring, ci ritroviamo con qualcosa di simile:
foreach (string currentTestCaseValue in TestCaseSets)
{
BusinessObject myCustomer = new BusinessObject();
SetDeepValue(myCustomer,()=>myCustomer.NameInfo.First,currentTestCaseValue);
ValidateBusinessRules(myCustomer);
}
Quando questo codice viene eseguito, si ottiene l'errore:
Object does not match target type.
Ho il sospetto che sta cercando di chiamare la proprietà First
sul BusinessObject
, al posto del NameInfo
. Come posso modificare il mio codice per gestire questo caso "annidato"?
Fornisci altre righe di programma e un esempio di propertyToValidate/objectUnderTest/eccessivamenteLargeNameValue. – xanatos
Sono abbastanza sicuro che per gli oggetti nidificati, devi effettivamente ottenere l'oggetto e quindi eseguire un'altra chiamata '.SetValue()' su quell'oggetto – JNYRanger
Vedere se http://stackoverflow.com/a/7723923/613130 è quello che ti serve ... Da un getter restituisce un setter d'azione – xanatos