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

Mos*_*aou 2 c# methods return-value

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

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

进入这个:

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

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

Dav*_*vid 6

不.替代方案是这样的:

var myStr = GetThatValue().Substring(1, GetThatValue().Length - 2);
Run Code Online (Sandbox Code Playgroud)

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

即使它不是一项昂贵的操作,这正是一个教科书案例,说明了什么变量......存储价值.


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

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

// later...
var myStr = GetThatValue().Substring(1, GetThatValue().Length - 2);
Run Code Online (Sandbox Code Playgroud)

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

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