0

考虑下面的类
- 我可以做任何事情来实现不区分大小写的字符串吗?

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);
    }
}

HTML 4 文档的结构

我已将课程编辑为更加客观和具体

4

5 回答 5

2

你不能有不区分大小写的属性——你只能有不区分大小写的操作,比如比较。如果有人访问 XHtmlOneDTDElementAttibute.Name,他们将得到一个字符串,无论它是用什么大小写创建的。

每当您使用 .Name 时,您都可以以忽略字符串大小写的方式实现该方法。

于 2009-05-31T21:16:41.010 回答
2

在回答重组后的问题时,您可以这样做:

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。

于 2009-05-31T21:42:01.223 回答
1

这取决于您要对字符串做什么。

如果要不考虑大小写比较字符串,请调用String.Equalswith StringComparison.OrdinalIgnoreCase。如果要将它们放入字典中,请制作字典的 comparer 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物业做什么

于 2009-05-31T21:19:04.907 回答
1

好吧,在浏览了规范之后,我对此的看法是,您不需要做任何事情来使字符串属性不区分大小写。无论如何,这个概念并没有真正的意义:字符串不区分大小写或不区分大小写;对它们的操作(如搜索和排序)是。

(我知道 W3C 的 HTML 建议基本上是这样说的。措辞很糟糕。)

于 2009-05-31T21:19:18.273 回答
1

或者,您可能希望使属性始终为大写,就像这样。

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; }
}
于 2009-05-31T21:34:01.677 回答