我有一个带有这个签名的函数:
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" );
}
}
我想知道这种使用空字符串和对象引用相等性的技术是否总是安全的,尤其是在字符串驻留方面。
请您参考如下方法:
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
