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

再構成された質問への回答として、次のようにすることができます。

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 に答える
2

大文字と小文字を区別しないプロパティを使用することはできません。比較など、大文字と小文字を区別しない操作のみを行うことができます。誰かが XHtmlOneDTDElementAttibute.Name にアクセスすると、大文字と小文字が区別された文字列が返されます。

.Name を使用するときはいつでも、文字列の大文字と小文字を無視する方法でそのメソッドを実装できます。

于 2009-05-31T21:16:41.010 に答える
1

文字列で何をしようとしているかによって異なります。

大文字と小文字を区別せずに文字列を比較したい場合は、 で呼び出しString.Equalsます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 に答える