从c#表达式获取对象的引用 [英] Get reference to object from c# expression

查看:303
本文介绍了从c#表达式获取对象的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个扩展通用方法

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?
}

我需要从表达式获取对TModel对象的引用。
此方法由以下代码调用:

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")


推荐答案

您不能将其传递到方法中,而不能访问TModel对象。你传递的表达只是说从一个TModel拿这个属性。实际上并没有提供TModel来操作。所以,我将重构这样的代码:

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")

这篇关于从c#表达式获取对象的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆