2013-05-19 19 views
1

我有這個簽名的函數:是一個字符串引用相等檢查保證是靜態的嗎?

public void DoSomething(String name); 

字符串name是在我的應用程序特殊。它可以是任意字符串,也可以是特定的已知值。因爲任何非空字符串值是不是就意味着我需要使用對象引用平等空字符串,像這樣一個有效的輸入:

public class Foo { 

    public const String SpecialValue1 = ""; 
    public const String SpecialValue2 = ""; 

    public void DoSomething(String name) { 

     if(Object.ReferenceEquals(name, SpecialValue1)) { 



     } else if(Object.ReferenceEquals(name, SpecialValue2) { 


     } else { 

     } 
    } 

    public void UsageExample() { 

     DoSomething(SpecialValue1); 
     DoSomething("some arbitrary value"); 
    } 
} 

我想,如果這種技術,使用空字符串和將對象引用相等知道總是很安全,特別是在串線實習方面。

+0

你有甚至嘗試'的ReferenceEquals(SpecialValue1,SpecialValue2)'?直接出現在源代碼(以及其他字符串,通過一些算法)中的跺跺[string interning](http://en.wikipedia.org/wiki/String_interning)。所以這與例如'public static readonly object SpecialValue1 = new object(); public static readonly object SpecialValue2 = new object();'。 –

+0

接受對象或枚舉的重載是正確的方法。 –

回答

3

Antimony is right about the reasons this will not work

我建議你爲參數定義一個類型。我們稱之爲ExampleArgument

public class ExampleArgument 
{ 
    private readonly int _knownValue; 
    private readonly string _arbitraryValue; 

    public ExampleArgument(string arbitraryValue) 
    { 
     _arbitraryValue = arbitraryValue; 
     _knownValue = 0; 
    } 

    private ExampleArgument(int knownValue) 
    { 
     _knownValue = knownValue; 
     _arbitraryValue = null; 
    } 

    public static readonly ExampleArgument FirstKnownValue = new ExampleArgument(1); 
    public static readonly ExampleArgument SecondKnownValue = new ExampleArgument(2); 

    // obvious Equals and GetHashCode overloads 

    // possibly other useful methods that depend on the application 
} 

哦,如果你真的想在你的榜樣的調用語法,你可以添加:

public static implicit operator ExampleArgument(string arbitraryValue) 
    { 
     return new ExampleArgument(arbitraryValue); 
    } 

這是從字符串ExampleArgument的隱式轉換操作符。

DoSomething(ExampleArgument.FirstKnownValue); 
DoSomething(new ExampleArgument("hello")); 
DoSomething("hello"); // equivalent to previous line, uses implicit conversion operator 
+0

我最終採用了這種方法 - 事實證明這是最好的決定,因爲我需要那些'ExampleArgument'類型的多態行爲。 – Dai

1

不,這不安全。事實上,這將永遠不會工作。字符串文字會被攔截,所以這兩個特殊值都會有相同的引用。大多數編譯器也將實習編譯時間常量字符串,並且您始終可以手動實習字符串。

不幸的是,如果你想接受任何有效的字符串,你需要一些其他的方式來傳遞額外的信息。即使像這樣的破解工作,這將是一個壞主意,因爲它違反了正常的字符串平等語義。

以下是可能的,我能想到的

  • 如果你只有一個特殊的價值,你可以使用空
  • 採取更廣泛的類型,如對象作爲輸入
  • 兩個參數
  • 製作一個單獨的功能
相關問題