簡體   English   中英

C#不區分大小寫的字符串

[英]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);
    }
}

HTML 4文檔的結構

我對課程進行了修改,使其更加客觀和具體

您不能具有不區分大小寫的屬性-您只能具有不區分大小寫的操作,例如比較。 如果有人訪問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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM