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

时间:2016-02-09 11:15:56

标签: c# methods return-value

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

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关键字,但它在此上下文中不起作用。它将按预期引用类实例。

3 个答案:

答案 0 :(得分:6)

不。另一种选择是:

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

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

即使它不是一项昂贵的操作,这也只是一个教科书案例,说明变量用于存储值。

但是,有可能有一个完全可以接受的场景。考虑C#的属性,它们实际上只是经典getter / setter方法的语法糖。如果我们看一下传统Java意义上的那些getter,我们可能会有这样的东西:

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

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

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

事实上,当getter有一些逻辑应该始终包含对该变量的访问时,通常会使用这种方法,即使对于仅限私有的成员也是如此。

答案 1 :(得分:3)

您可以尝试这种方式(使用临时变量):

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

或(甚至更短):

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

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

答案 2 :(得分:0)

另一个替代 - 制作扩展方法:

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(), "^.", ""), ".$", "");