Get reference to object from c# expression

走远了吗. 提交于 2020-01-17 01:29:26

问题


I have an extension generic method

public static void AddError<TModel>(
    this ModelStateDictionary modelState, 
    Expression<Func<TModel, object>> expression, 
    string resourceKey, 
    string defaultValue)
{
    // How can I get a reference to TModel object from expression here?
}

I need to get the reference to TModel object from expression. This method called by the following code:

ModelState.AddError<AccountLogOnModel>(
    x => x.Login, "resourceKey", "defaultValue")

回答1:


You cannot get to the TModel object itself without passing it into the method. The expression you are passing in is only saying "take this property from a TModel". It isn't actually providing a TModel to operate on. So, I would refactor the code to something like this:

public static void AddError<TModel>(
    this ModelStateDictionary modelState, 
    TModel item,
    Expression<Func<TModel, object>> expression, 
    string resourceKey, 
    string defaultValue)
{
    // TModel's instance is accessible through `item`.
}

Then your calling code would look something like this:

ModelState.AddError<AccountLogOnModel>(
    currentAccountLogOnModel, x => x.Login, "resourceKey", "defaultValue")



回答2:


I imagine you really want the text "Login" to use to add a new model error to the ModelStateDictionary.

public static void AddError<TModel>(this ModelStateDictionary modelState, 
  Expression<Func<TModel, object>> expression, string resourceKey, string defaultValue)
{
    var propName = ExpressionHelper.GetExpressionText(expression);

    modelState.AddModelError(propName, GetResource("resourceKey") ?? defaultValue);
}

Assume you have some resource factory/method that returns null if the resource isn't found, that's just for illustration.



来源:https://stackoverflow.com/questions/8793799/get-reference-to-object-from-c-sharp-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!