[英]C# 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);
}
}
我对课程进行了修改,使其更加客观和具体
您不能具有不区分大小写的属性-您只能具有不区分大小写的操作,例如比较。 如果有人访问XHtmlOneDTDElementAttibute.Name,则无论使用哪种大小写方式,他们都将返回一个字符串。
每当使用.Name时,都可以以忽略字符串大小写的方式来实现该方法。
为了回答重组后的问题,您可以这样做:
public class Attribute { public string Name { get; set; } }
public class AttributeCollection : KeyedCollection<string, Attribute> {
public AttributeCollection() : base(StringComparer.OrdinalIgnoreCase) { }
protected override string GetKeyForItem(Attribute item) { return item.Name; }
}
public class ClassWithAttributes {
private AttributeCollection _attributes;
public void AddAttribute(Attribute attribute) {
_attributes.Add(attribute);
//KeyedCollection will throw an exception
//if there is already an attribute with
//the same (case insensitive) name.
}
}
如果使用此方法,则应将Attribute.Name
只读,或在更改时调用ChangeKeyForItem。
这取决于您要对字符串进行的处理。
如果要比较大小写的字符串,请使用StringComparison.OrdinalIgnoreCase
调用String.Equals
。 如果要将它们放入字典中,请使该字典的比较器StringComparer.OrdinalIgnoreCase
。
因此,您可以执行以下功能:
public class XHtmlOneDTDElementAttibute : ElementRegion {
public bool IsTag(string tag) {
return Name.Equals(tag, StringComparison.OrdinalIgnoreCase);
}
// The Name should be case-insensitive
public string Name { get; set; }
// The Value should be case-sensitive
public string Value { get; set; }
}
如果您需要更具体的解决方案,请告诉我Name
属性的作用
好吧,在看完规范之后,我对此的看法是,您无需执行任何操作即可使字符串属性不区分大小写。 无论如何,这个概念并没有真正的意义:字符串不区分大小写或不区分大小写。 对它们的操作(如搜索和排序)。
(我知道W3C的HTML建议本质上就是这样。措辞很差。)
另外,您可能希望使属性始终为大写,如下所示。
public class XHtmlOneDTDElementAttibute : ElementRegion {
string name;
// The Name should be case-insensitive
public string Name {
get { return name; }
set { name = value.ToUpperInvariant(); }
}
// The Value should be case-sensitive
public string Value { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.