gpt4 book ai didi

c# - 字符串引用相等性检查是否保证是静态的?

转载 作者:太空宇宙 更新时间:2023-11-03 21:46:42 25 4
gpt4 key购买 nike

我有一个带有这个签名的函数:

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

关于c# - 字符串引用相等性检查是否保证是静态的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16631814/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com