为什么在下面的示例中第一个(x)为真,第二个(y)为假?
我想在C#中使用类似VB的运算符.
我想在C#中使用类似VB的运算符.
Dim x = "abc@symas-design.ch" Like "*symas-design.ch" Dim y = Microsoft.VisualBasic.CompilerServices.Operators.LikeString("abc@symas-design.ch","*symas-design.ch",CompareMethod.Text)
Like运算符显然不使用Operators.LikeString,而是使用LikeOperator.LikeString.
我试过这个LINQPad程序:
Sub Main Dim x = "abc@symas-design.ch" Like "*symas-design.ch" Dim y = Microsoft.VisualBasic.CompilerServices.Operators.LikeString("abc@symas-design.ch",Microsoft.VisualBasic.CompareMethod.Text) x.Dump() y.Dump() End Sub
它显示:
True False
正如你所说,他们不会这样做,但后来我展示了IL生成:
IL_0000: ldstr "abc@symas-design.ch" IL_0005: ldstr "*symas-design.ch" IL_000A: ldc.i4.0 IL_000B: call Microsoft.VisualBasic.CompilerServices.LikeOperator.LikeString IL_0010: stloc.0 // x IL_0011: ldstr "abc@symas-design.ch" IL_0016: ldstr "*symas-design.ch" IL_001B: ldc.i4.1 IL_001C: call Microsoft.VisualBasic.CompilerServices.Operators.LikeString IL_0021: stloc.1 // y IL_0022: ldloc.0 // x IL_0023: call LINQPad.Extensions.Dump IL_0028: pop IL_0029: ldloc.1 // y IL_002A: call LINQPad.Extensions.Dump
Sub Main Dim x = "abc@symas-design.ch" Like "*symas-design.ch" Dim y = Microsoft.VisualBasic.CompilerServices.Operators.LikeString("abc@symas-design.ch",Microsoft.VisualBasic.CompareMethod.Text) Dim z = Microsoft.VisualBasic.CompilerServices.LikeOperator.LikeString("abc@symas-design.ch",Microsoft.VisualBasic.CompareMethod.Text) x.Dump() y.Dump() z.Dump() End Sub
我得到了:
True <-- Like operator False <-- Operator.LikeString True <-- LikeOperator.LikeString
所以你需要使用LikeOperator.LikeString.
这是一个C#LINQPad程序,演示:
void Main() { bool z = LikeOperator.LikeString("abc@symas-design.ch",Microsoft.VisualBasic.CompareMethod.Text); z.Dump(); }
哪个也输出True.