简体   繁体   English

函数返回的字符串

[英]string returned by function

If I write the following code : 如果我写下面的代码:

if(string.IsNullOrEmpy(myObj.GetString()))
{
  var myString  = myObj.GetString() + myObj.GetString();
}

My function GetString() will be called 3 times, then it can execute some complex code 3times. 我的函数GetString()将被调用3次,然后它可以执行3次复杂的代码。 Is there a simpler way than : 有没有比以下更简单的方法:

var firstString = myObj.GetString();
if(!string.IsNullOrEmpy(firstString))
{
  var myString  = firstString  + firstString;
}

to have only one execution of the code in GetString() ? 在GetString()中只执行一次代码?

You COULD make it more complex and have an IsChanged bool value, and if anything in the object changes set IsChanged to true and then rebuild the string, else return the last string built, but then you'd need to add synchronization and it probably wouldn't be worth the cost. 您可以使它更复杂并具有IsChanged bool值,如果对象更改中的任何内容将IsChanged设置为true然后重建字符串,否则返回构建的最后一个字符串,但是您需要添加同步并且它可能不会不值这笔钱。

So, the long and the short is that the 2nd case is generally the best case. 所以,长期和短期是第二种情况通常是最好的情况。 It's simple and straightforward and efficient. 它简单明了,高效。

UPDATE : It's hard to tell what the update scenario is here. 更新 :很难说出更新方案在这里。 So let's look at several. 那么让我们看看几个。

1). 1)。 If you are only updating the string on demand from the application, and that string is created using some complex method, just have a new update method and then return the current string as a property. 如果您只是按需从应用程序更新字符串,并且使用某种复杂方法创建该字符串,则只需使用新的更新方法,然后将当前字符串作为属性返回。 Then, you can just query the MyString property and it will be a simple return. 然后,您可以只查询MyString属性,它将是一个简单的返回。

public class SomeClass
{
    public string MyString { get; private set; }

    public void UpdateString(...)
    {
       // DO YOUR COMPLEX LOGIC

       MyString = ... new value ...
    }
}

2). 2)。 Or, if it's just a simple string with no complex logic, you could have the application responsible for creating and assigning it: 或者,如果它只是一个没有复杂逻辑的简单字符串,您可以让应用程序负责创建和分配它:

public class SomeClass
{
    public string MyString { get; set; }
}

...

myObj.MyString = SomeComplexLogicToBuildString();

But as I said, that's only if the string representation is independent from the state of the object. 但正如我所说,只有当字符串表示独立于对象的状态时才会这样。

3). 3)。 If it's based on the state of the object and changes when the object state changes, you could let the string be re-created whenever something changes: 如果它基于对象的状态并在对象状态更改时发生更改,则可以在发生更改时重新创建字符串:

public class SomeClass
{
    private bool _hasChanged = true;
    private string _previousString = null;


    public string MyString
    {
        get 
        {
            if (_hasChanged)
            {
                _hasChanged = false;
                _previousString = .... your complex string building logic ....
            } 

            return _previousString;
        }
    }

    public int OtherProperties
    {
        get { return _otherField; }
        set { _otherField = value; _hasChanged = true; }
    }

But once again, you'd probably want to synchronize this if it's multi-threaded use. 但是再一次,如果它是多线程使用的话,你可能想要同步它。

BUT This is all IF you want to cache the value so it's not rebuilt each time as a responsibility of the class itself. 但是, 如果你想缓存这个值,那么每次都不会重建它作为类本身的责任。

Truly, your simplest and best bet is just to use your second method, and if you are using it several times in one method just set to a temporary variable and use that. 确实,你最简单和最好的选择就是使用你的第二种方法,如果你在一种方法中多次使用它,只需设置一个临时变量并使用它。

As an alternative: 作为备选:

var firstString = myObj.GetString();
var myString  = string.Concat(firstString, firstString);

string.Concat already manages the null case (treating it as an empty string). string.Concat已经管理了null case(将其视为空字符串)。

Another option would be to cache the results after the first call to GetString. 另一种选择是在第一次调用GetString后缓存结果。 Then subsequent calls would use the cached copy. 然后后续调用将使用缓存副本。 But the way you're doing it is fine for most cases and simpler than implementing a cache. 但是,对于大多数情况而言,这样做的方式很好,并且比实现缓存更简单。

Try something like this 尝试这样的事情

public static void Main(string[] args) 
    {
        string s;
        if((s=getString())!=null) 
        {
            Console.WriteLine(s);
            Console.ReadLine();
        }
    }

    static string getString() 
    {
        return "hello";
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM