[英]How to implement contains operator in C#
I'm creating dynamic converter which converts Visual FoxPro expression to C# expressions which are used in Razor views. 我正在创建动态转换器,它将Visual FoxPro表达式转换为Razor视图中使用的C#表达式。
FoxPro has contains operator $
FoxPro包含运算符
$
a $ b
returns true if a if substring of b like Contains(a,b) : 如果b的if子字符串如Contains(a,b),则返回true:
public static bool Contains(string a, string b)
{
if (a == null || b == null)
return false;
return b.Contains(a);
}
Replacing $
operator with this Contains method call requires creating sophisticated parser. 用此Contains方法调用替换
$
运算符需要创建复杂的解析器。 Not sure how this parser can implemented. 不确定该解析器如何实现。
a$b
can be part of expression, a
and b
can be string expressions. a$b
可以是表达式的一部分, a
和b
可以是字符串表达式。
How to make it work ? 如何使其工作? Is is possible to implement contains operator ( operator name can changed, parser can emit it easily) ?
是否可以实现包含运算符(运算符名称可以更改,解析器可以轻松地发出它)? Or is there some other way to avoid manual conversion of FoxPro expressions ?
还是有其他方法可以避免手动转换FoxPro表达式?
Expressions are used in C# Razor Views in ASP.NET MVC4 application. 在ASP.NET MVC4应用程序的C#剃刀视图中使用表达式。
Update 更新资料
I can use standard operator, for example %
. 我可以使用标准运算符,例如
%
。 How to implement a % b
operator in Razor views for strings which returns true if a contains in b ? 如何在Razor视图中为字符串实现
a % b
运算符,如果a包含在b中,则该字符串返回true?
Operator overloading is only possible with known operators: +
, *
, ==
, etc. $
is not a known operator so it is not possible what you want to do. 运算符重载仅适用于已知的运算符:
+
, *
, ==
等。 $
不是已知的运算符,因此无法执行您想做的事情。
You can use the new roslyn platform to change the language itself and make it possible (see the presentation at Build 2014 where they demonstrate how to use fancy accents to denote a string instead of "
). 您可以使用新的roslyn平台来更改语言本身,并使其成为可能(请参阅Build 2014上的演示,其中他们演示如何使用花哨的重音符号来表示字符串而不是
"
)。
In textform (see: " Example of updating the compiler "): MSDN Blogs: Taking a tour of Roslyn 以文本形式(请参阅:“ 更新编译器的示例 ”): MSDN博客:参观Roslyn
What you can do is use an extension method to simplify the job of your "parsing" tool. 您可以做的是使用扩展方法来简化“分析”工具的工作。
If you put a method such as this: 如果您放置这样的方法:
public static bool FPContains(this string a, string b)
{
if (a == null || b == null)
return false;
return b.Contains(a);
}
in a static class (that's an important constraint), then you can use your new FPContains
method as though it were directly implemented in the string
type, such as: 在静态类中(这是一个重要的约束),那么您可以使用新的
FPContains
方法,就好像它是直接在string
类型中实现的,例如:
bool isContained = string1.FPContains(string2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.