簡體   English   中英

生成一個 C# 表達式,可以將兩個字符串連接在一起

[英]Generate a C# expression that can concatenate two strings together

我試圖在動態 linq 表達式中將兩個字符串連接在一起。 我傳遞給 function 的參數必須是Dictionary<string, object> 問題是 The Expression.Add 向我拋出一個錯誤,因為它不知道如何添加字符串。

我想要達到的目標:

x => (string)x["FirstName"] + " Something here..."

我擁有的:

var pe = Expression.Parameter(typeof(Dictionary<string, object>), "x");
var firstName = Expression.Call(pe, typeof(Dictionary<string, object>).GetMethod("get_Item"), Expression.Constant("FirstName"));
var prop = Expression.Convert(firstName, typeof(string));
var exp = Expression.Add(prop, Expression.Constant(" Something here..."))

添加字符串既不是表達式顯式處理的類型之一(就像它對數字基元所做的那樣),也不會由於+的重載而起作用(因為string沒有這樣的重載),因此您需要顯式定義應該是的方法重載時調用:

Expression.Add(
  prop,
  Expression.Constant(" Something here..."),
  typeof(string).GetMethod("Concat", new []{typeof(string), typeof(string)}))

這使得使用兩個字符串參數的string.Concat的重載成為使用的方法。

您也可以使用Expresssion.Call但這會使您的+意圖明確(因此,這是 C# 編譯器在生成表達式時所做的事情)。

添加和連接是完全不同的過程。 當您將兩個字符串“添加”在一起時,您將它們連接起來,因為對字符串進行數學加法是沒有意義的。

連接字符串的最佳方法是使用String.Concat 您可以使用Expression.Call生成方法表達式:

// Create the parameter expressions
var strA = Expression.Parameter(typeof(string));
var strB = Expression.Parameter(typeof(string));

// Create a method expression for String.Join
var methodInfo = typeof(string).GetMethod("Concat", new[] { typeof(string), typeof(string) });
var join = Expression.Call(methodInfo, strA, strB);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM