如何在后续方法中引用方法return值?

How to reference a method return value in a subsequent method?

我只是想知道是否有办法简化这段代码:

var myStr = GetThatValue();
myStr = myStr.Substring(1, myStr.Length - 2); // remove first and last chars

进入这个:

// how to get hold of GetThatValue return value?
var myStr = GetThatValue().Substring(1, hereWhat.Length - 2);

我虽然关于 this 关键字,但它在这种情况下不起作用。它将按预期引用 class 实例。

没有。替代方案是:

var myStr = GetThatValue().Substring(1, GetThatValue().Length - 2);

如您所见,它调用了 GetThatValue() 两次。因此,如果该操作很昂贵或 returns 不同的值,那么它可能不应该被重新调用。

即使这不是一项昂贵的操作,这也正是变量用于...存储值的教科书案例。


不过,有可能出现完全可以接受的情况。考虑 C# 的属性,它们实际上只是 classic getter/setter 方法的语法糖。如果我们从传统的 Java 的角度来看那些 getter,我们可能会有这样的东西:

private thatValue;
public string GetThatValue() { return someString; }

// later...
var myStr = GetThatValue().Substring(1, GetThatValue().Length - 2);

在这种情况下,这不是一项昂贵的操作,也不会 return 不同的值。 (尽管有线程。)在这种情况下,使用变量与方法之间没有明显的逻辑差异,因为方法只是 class 级变量的包装器。

事实上,当 getter 有一些逻辑应该始终包装对该变量的访问时,即使是私有成员,也经常使用这种方法。

你可以这样试试(使用临时变量):

string temp;
var myStr = (temp = GetThatValue()).Substring(1, temp.Length - 2);

或(更短):

string myStr = (myStr = GetThatValue()).Substring(1, myStr.Length - 2);

它也有效。您必须在声明 myStr 变量时将 var 更改为 string

另一种选择 - 制作扩展方法:

public static class Util
{
    public static string Trim(this string input, int headTrim, int tailTrim)
    {
        return input.Substring(headTrim, input.Length - headTrim - tailTrim);
    }
}

用法:

var str = GetThatValue().Trim(1, 1);

一行解法(仅供练习)

删除第一个和最后一个字符的正则表达式

string result = Regex.Replace(Regex.Replace(GetThatValue(), "^.", ""), ".$", "");