データベースからデータ型へのマッピングパラメータを処理する次のコードを記述しました(標準ORMを使用することはできますが、多くの理由)式を使用してパラメータを設定する方法<Func<T>>
public void LoadDatabaseValue<T>(DataTable partData, string identifier, string mappingName, Expression<Func<T>> mappingProperty)
{
var partAttributeValue = mappingProperty.Name;
var memberExpression = (MemberExpression)mappingProperty.Body;
var prop = (PropertyInfo)memberExpression.Member;
try
{
var selectedRow = partData.Select($"partattributename = '{mappingName}'");
var selectedValue = selectedRow[0]["PartAttributeValue"];
var typedOutput = (T)Convert.ChangeType(selectedValue, typeof(T));
prop.SetValue(memberExpression.Expression, typedOutput, null);
}
catch (Exception exception)
{
_databaseImportError = true;
// code to log this error
}
私はこれを実行しようとすると、私は私の財産の種類と、それ私のtypedOutputラインをデバッグする、それが投げている理由は、私がわからないときは、私は次の例外
{System.Reflection.TargetException: Object does not match target type.
at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target)
at System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, Object[] index) }
を取得この例外。
私はSetValue
の最初のパラメータが値を設定するプロパティを含むオブジェクトである必要があります例えば
LoadDatabaseValue(partData, identifier, "Offset",() => Offset);
あなたは 'Func'を渡すが、それは'式> 'であることを期待しています。どちらかを同じタイプに変更してください。 –
Venky
@Venky彼は式を渡しています。 – Servy