简体   繁体   English

在机器对机器通信场景中使用的正确字符串比较值是什么?

[英]What is the right string comparison value to be used in a machine to machine communication scenario?

Consider a scenario where you are implementing code meant to be used for machine to machine communication.考虑一个场景,您正在实现旨在用于机器对机器通信的代码。 The typical example for that is the code executed inside a web API action method.典型的例子是在 web API 操作方法中执行的代码。

Suppose that you want to perform an exact match between strings;假设您要在字符串之间执行完全匹配; maybe you have a list of users and you wan to find one specific user provided the user name:也许您有一个用户列表,并且您希望找到一个提供用户名的特定用户:

List<User> users = ....
const string username = "user-123";
var user = users.Find(u => string.Equals(username, u.UserName));

In such a scneario should I use StringComparison.Ordinal or StringComparison.InvariantCulture ?在这样的场景中,我应该使用StringComparison.Ordinal还是StringComparison.InvariantCulture

Based on my understanding, since I want to perform an exact match between two strings, the proper choice here is StringComparison.Ordinal .根据我的理解,由于我想在两个字符串之间执行完全匹配,所以这里的正确选择是StringComparison.Ordinal

The typical example for culture sensitive comparison between the two strings Straße and strasse , where the two strings are considered equal due to linguistical rules, does not seem to fit here.两个字符串Straßestrasse之间的文化敏感比较的典型示例,其中两个字符串由于语言规则被认为是相等的,似乎不适合这里。

Is this assumption correct?这个假设正确吗?

If this is correct, can you provide an example where using the invariant culture instead of the ordinal comparison is the right choice?如果这是正确的,您能否提供一个示例,说明使用不变文化而不是序数比较是正确的选择?

Just to clarify, I'm asking because I'm working on a code base where there are plenty of string comparisons using the invariant culture.只是为了澄清,我问是因为我正在开发一个代码库,其中有大量使用不变文化的字符串比较。 Many of these cases refer to exact string match performed in a machine to machine communication scenario .其中许多情况是指在机器对机器通信场景中执行的精确字符串匹配 So I want to be sure to clearly understand the rationale behind the right choice of a string comparison value.所以我想确保清楚地理解正确选择字符串比较值背后的基本原理。

It would seem from the details provided that you are correct in your assumption - you want to find a specific user where the name is "Bob".从提供的详细信息看来,您的假设是正确的 - 您想找到名称为“Bob”的特定用户。 "Bób" is a different user and should not match, ie you are actually trying to match two symbols, and not how the username would be read. “Bób” 是不同的用户,不应该匹配,即您实际上是在尝试匹配两个符号,而不是用户名的读取方式。

If, however, you were looking up street names, you may want to ask the code to consider "strasse" and "Straße" to be considered as the same, as you are doing a linguistic match ie would the client read these two things in the same way.但是,如果您正在查找街道名称,您可能想要求代码将“strasse”和“Straße”视为相同,因为您正在进行语言匹配,即客户是否会在一样的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM