C# 不区分大小写的字符串
考虑下面的类
- 我可以做些什么来实现不区分大小写的字符串吗?
public class Attibute
{
// The Name should be case-insensitive
public string Name
{
get;
set;
}
public Attibute()
{
}
}
public class ClassWithAttributes
{
private List<Attributes> _attributes;
public ClassWithAttributes(){}
public AddAttribute(Attribute attribute)
{
// Whats the best way to implement the check?
_attributes.add(attribute);
}
}
我已经编辑了课程,使其更加客观和具体
Considering the class below
- can I do anything to implement a case-insensitive string?
public class Attibute
{
// The Name should be case-insensitive
public string Name
{
get;
set;
}
public Attibute()
{
}
}
public class ClassWithAttributes
{
private List<Attributes> _attributes;
public ClassWithAttributes(){}
public AddAttribute(Attribute attribute)
{
// Whats the best way to implement the check?
_attributes.add(attribute);
}
}
Structure of an HTML 4 Document
I have edited the class to be a bit more objective and specific
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
为了回答重组问题,您可以这样做:
如果您使用它,您应该将 Attribute.Name 设置为只读,或者在更改时调用 ChangeKeyForItem。
In answer to the restructured question, you could do it like this:
If you use this, you should either make
Attribute.Name
read-only or call ChangeKeyForItem whenever it's changed.您不能具有不区分大小写的属性 - 只能具有不区分大小写的操作,例如比较。 如果有人访问 XHtmlOneDTDElementAttibute.Name,他们将返回一个字符串,无论其创建时的大小写如何。
每当您使用 .Name 时,您都可以以忽略字符串大小写的方式实现该方法。
You can't have case-insensitive properties—you can only have case-insensitive operations, like a comparison. If someone accesses XHtmlOneDTDElementAttibute.Name, they will get back a string with whatever case it was created with.
Whenever you use .Name, you can implement that method in a way that ignores the case of the string.
这取决于你想用字符串做什么。
如果您想要比较字符串而不考虑大小写,请使用
StringComparison.OrdinalIgnoreCase
调用String.Equals
。如果您想将它们放入字典中,请将字典的比较器设置为
StringComparer.OrdinalIgnoreCase
。因此,您可以创建一个函数,如下所示:
如果您想要更具体的解决方案,请告诉我您正在使用
Name
属性做什么It depends what you're trying to do with the strings.
If you want to compare strings regardless of case, call
String.Equals
withStringComparison.OrdinalIgnoreCase
.If you want to put them in a dictionary, make the dictionary's comparer
StringComparer.OrdinalIgnoreCase
.Therefore, you could make a function as follows:
If you want a more specific solution, please tell me what you're doing with the
Name
property好吧,在浏览了规范之后,我对此的看法是,您无需执行任何操作即可使字符串属性不区分大小写。 无论如何,这个概念并没有真正意义:字符串不区分大小写或不区分大小写; 对它们的操作(如搜索和排序)是。
(我知道 W3C 的 HTML 建议本质上就是这么说的。它的措辞很糟糕。)
Well, my take on this, after glancing at the spec, is that there's nothing you need to do to make the string properties case-insensitive. The concept doesn't really make sense, anyway: strings aren't case-sensitive or -insensitive; operations on them (like search and sort) are.
(I know the W3C's HTML recommendations say essentially that. It's badly-phrased.)
或者,您可能希望使属性始终大写,如下所示。
Alternatively, you might want to make the property always uppercase, like this.