[英]Why is there a name clash between generic type parameter and other members
[英]Name clash between class static member and another type
我剛剛宣布
public static class DefaultComparers
{
public readonly IComparer TextComparer = new TextComparer(new CompositeIndexedComparer<string>());
private static IDictionary<string, IComparer> DefaultComparers()
{
return new Dictionary<string, IComparer>(StringComparer.InvariantCultureIgnoreCase) {
{"txt", TextComparer}
};
}
}
但是,在同一個名稱空間中已經有一個名為TextComparer
的類,因此DefaultComparers
方法無法編譯。 如果它是非靜態方法,則可以使用this.TextComparer
輕松修復它。 在靜態上下文中有什么替代方案?
該方法的名稱與您的類相同,但不能相同,編譯器假定它為您的類的構造函數,因此它不應具有返回類型
private static IDictionary<string, IComparer> DefaultComparers()
{
return new Dictionary<string, IComparer>(StringComparer.InvariantCultureIgnoreCase) {
{"txt", TextComparer}
};
}
您的問題似乎基於錯誤的前提。 您的代碼還有其他一些問題,但是您所要求的問題不存在。 這可以完美地編譯:
class ConflictName
{
}
class GoodName
{
static object ConflictName = new ConflictName();
static Dictionary<string, object> ANOTHERGoodName()
{
return new Dictionary<string, object>
{
{ "txt", ConflictName }
};
}
}
編譯器知道一個類型 (之間的差class ConflictName
)和值 (字段ConflictName
第二類的內部)。
但是,在其他需要限定static
成員的情況下(例如,因為它被同一方法中定義的局部變量隱藏了),您只需在類名GoodName.ConflictName
前綴即可,例如GoodName.ConflictName
而不是ConflictName
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.