简体   繁体   English

从C#表达式获取对对象的引用

[英]Get reference to object from c# expression

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. 我需要从表达式获取对TModel对象的引用。 This method called by the following code: 此方法由以下代码调用:

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

You cannot get to the TModel object itself without passing it into the method. 如果不将TModel对象传递给方法,则无法访问它本身。 The expression you are passing in is only saying "take this property from a TModel". 您传递的表达式只是说“从TModel获取此属性”。 It isn't actually providing a TModel to operate on. 它实际上并没有提供要运行的TModel。 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")

I imagine you really want the text "Login" to use to add a new model error to the ModelStateDictionary . 我想您真的希望文本“ Login”用于向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. 假设您有一些资源工厂/方法,如果找不到该资源,则返回null ,这仅用于说明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM