2012-01-09 56 views
0

反對我有一個擴展的通用方法獲取參考從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的對象。 該方法通過下面的代碼名爲:

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

有一個表達式沒有這樣的對象 - 'x'是一個參數的表達,你應該將類型的對象傳遞給它。 (或者我正在理解你想要實現的錯誤。) – millimoose 2012-01-09 19:14:27

+0

感謝您的回覆,Inerdial) – 2012-01-09 19:18:23

+1

您是否真的希望爲AddModelError(key,errorMessage)方法使用對象或文本'Login'?使用'ExpressionHelper.GetExpressionText'(內置於MVC)從lambda表達式獲取屬性名稱。 – kamranicus 2012-01-09 19:24:47

回答

1

如果不將它傳遞給方法,你不能進入TModel對象本身。你傳遞的表達只是說「從TModel獲取這個屬性」。它實際上並不提供一個TModel來進行操作。所以,我的代碼重構是這樣的:

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`. 
} 

然後調用代碼會是這個樣子:

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

感謝您的回覆,我也沒有看到另一種方式。我昨天已經在我的代碼中完成了^) – 2012-01-10 06:21:50

0

我想你真正想要的文本「登錄」,使用一個新的模型錯誤添加到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); 
} 

假設你有一些資源工廠/方法返回null如果找不到資源,這只是爲了說明。

+0

感謝您的回覆,但我需要將我的錯誤數據(如資源鍵和默認值)保存到modelState對象和TModel對象中。通過表達式,我將屬性傳遞給哪個錯誤數據,這些屬性應該保存到TModel對象中。 ) – 2012-01-09 19:36:08

+1

爲此,您需要傳入實際對象作爲參數。泛型不是對象引用本身。 – kamranicus 2012-01-09 20:05:07