2011-10-22 70 views
6

我想創建一個表達式樹。我需要從數據表中讀取數據並檢查其列。只有在運行時才知道要檢查的列以及要檢查的列數。列名以字符串數組的形式給予我,並且每列都有一個要檢查的字符串列表。我嘗試了以下示例表達式樹。錯誤靜態方法需要空實例,非靜態方法需要非空實例

這裏我遇到了一個錯誤。

靜態方法需要空實例,非靜態方法需要非空實例。 參數名稱:實例

在線路

內= Expression.Call(rowexp,MI,colexp);

請幫助我!

IQueryable<DataRow> queryableData = CapacityTable 
    .AsEnumerable() 
    .AsQueryable() 
    .Where(row2 => values.Contains(row2.Field<string>("Head1").ToString()) 
       && values.Contains(row2.Field<string>("Head2").ToString())); 

MethodInfo mi = typeof(DataRowExtensions).GetMethod(
    "Field", 
     new Type[] { typeof(DataRow),typeof(string) }); 

mi = mi.MakeGenericMethod(typeof(string)); 

ParameterExpression rowexp = Expression.Parameter(typeof(DataRow), "row"); 
ParameterExpression valuesexp = Expression.Parameter(typeof(List<string>), "values"); 
ParameterExpression fexp = Expression.Parameter(typeof(List<string>), "types"); 
Expression inner, outer, predicateBody = null; 

foreach (var col in types) 
{ 
    // DataRow row = CapacityTable.Rows[1]; 

    ParameterExpression colexp = Expression.Parameter(typeof(string), "col"); 
    // Expression left = Expression.Call(pe, typeof(string).GetMethod("ToLower", System.Type.EmptyTypes)); 

    inner = Expression.Call(rowexp,mi, colexp); 
    outer = Expression.Call(valuesexp, typeof(List<string>).GetMethod("Contains"), inner); 
    predicateBody = Expression.And(predicateBody,outer); 
} 

MethodCallExpression whereCallExpression = Expression.Call(
    typeof(Queryable), 
    "Where", 
    new Type[] { queryableData.ElementType }, 
    queryableData.Expression, 
    Expression.Lambda<Func<DataRow,bool>>(predicateBody, new ParameterExpression[] { rowexp })); 

回答

9

這意味着該方法調用你要代表的是靜態的,但你給它的目標表達。這就像試圖撥打電話:

Thread t = new Thread(...); 
// Invalid! 
t.Sleep(1000); 

你有點試圖在表達式樹形式,這是不允許的。

它看起來像發生這種情況的Field擴展方法上DataRowExtensions - 這樣的擴展方法的「目標」需要被表達爲第一參數的號召,因爲你真的想撥打:

DataRowExtensions.Field<T>(row, col); 

所以,你想:

inner = Expression.Call(mi, rowexp, colexp); 

,將調用this overload這是調用靜態方法有兩個參數的方式。

+0

你可能可以詳細介紹一下上面的內容嗎?爲什麼在這裏將Expression info作爲第一個參數傳遞給Expression.Call方法? – Kobojunkie

+0

@Kobojunkie:因爲這就是你如何告訴'Expression.Call'我們感興趣的靜態方法。請參閱http://msdn.microsoft.com/en-us/library/bb301084.aspx –

相關問題