I have a dynamic method GetAverage()
using reflection to calculate an average value for a list of string values. The string values are dynamically converted to a type determined in ValueType
. The type DataSet
contains a List<string>
:
public class AggregateController {
private List<DataSet> DataSets { get; set; }
private Type ValueType { get; set; }
public string GetAverage () {
dynamic sum = Activator.CreateInstance(this.ValueType);
this.DataSets.ForEach(x => {
var mI = this.TransformInputValue(x[0]);
return (dynamic)mI.Invoke(this, new object[] { value });
});
return sum.Average().ToString();
}
private dynamic TransformInputValue (string value) {
try {
var mI = this.ValueType.GetMethod("Parse", new Type[] { typeof(string) });
return (dynamic)mI.Invoke(this, new object[] { value });
} catch {
return null;
}
}
}
This method does everything perfectly when the given values are numeric values. Now I want to achieve dynamically calculating average values for timestamp values with the same method. The problem is that there is no Average()
extension method for TimeStamp objects and I do not mean to additionally implement a condition checking for timestamp values like this:
if (this.ValueType == typeof(TimeStamp)) {
//do stuff to calculate TimeStamp average.
} else {
return sum.Average().ToString();
}
Is there a way to dynamically react to types like TimeStamp
which have no Average()
extension method?
Aucun commentaire:
Enregistrer un commentaire