简体   繁体   English

如何确定字符串变量的值是否在C#中更改?

[英]How do I determine if the value of a string variable changed in C#?

I have something to do under a button click (add values to listbox) only if a particular string changes from its previous value. 只有当特定字符串从其先前值更改时,我才能通过按钮单击(将值添加到列表框)来执行操作。 How do I manage this? 我该如何管理? Below is a sample of my code: 以下是我的代码示例:

    private void button6_Click(object sender, EventArgs e)
    {
        string x = //some varying value I get from other parts of my program
        listBox1.Items.Clear();
        listBox1.Items.Add(x + /*other things*/);   
    }

I can at times have same value for string x from previous value when clicking button6. 单击button6时,我有时可以从前一个值获得与string x相同的值。 In such cases I don't want listBox1 to add the item (string x). 在这种情况下,我不希望listBox1添加项目(字符串x)。 How to add to listbox only when value of string changes? 如何在字符串值更改时添加到列表框? There's no way to predetermine string x . 没有办法预先确定string x It gets value when program is running. 它在程序运行时获得价值。

Note: adding values to listBox1 every single time and later deleting the duplicates wont work in my program. 注意:每次向listBox1添加值,之后删除重复项在我的程序中不起作用。

Have you considered keeping a copy of the old string value around in a private field, and simply comparing the new value to the old value to see if they match? 您是否考虑在私有字段中保留字符串值的副本,并简单地将新值与旧值进行比较以查看它们是否匹配?

For example: 例如:

// holds a copy of the previous value for comparison purposes
private string oldString = string.Empty; 

private void button6_Click(object sender, EventArgs e)
{
    // Get the new string value
    string newString = //some varying value I get from other parts of my program

    // Compare the old string to the new one
    if (oldString != newString)
    {
        // The string values are different, so update the ListBox
        listBox1.Items.Clear();
        listBox1.Items.Add(x + /*other things*/);   
    }

    // Save the new value back into the temporary variable
    oldString = newString;
}

Edit: As the other answers suggest, there are certainly other, more complicated solutions, like encapsulating all access to the string value in a property, or wrapping the string in a custom class. 编辑:正如其他答案所示,当然还有其他更复杂的解决方案,比如封装对属性中字符串值的所有访问,或者将字符串包装在自定义类中。 Some of these alternatives have the potential to be "cleaner", more object-oriented approaches. 其中一些替代方案有可能成为“更清洁”,更加面向对象的方法。 But they're all more complicated than simply saving the previous value in a field. 但它们比简单地保存字段中的先前值更复杂。 It's up to you to decide whether your specific use case merits the complicated solution, or a simpler one. 由您决定您的特定用例是否适合复杂的解决方案,或者更简单的解决方案。 Think about long-term maintainability, not what's easier for you to implement right now. 考虑长期可维护性,而不是现在更容易实现的。

string last = string.Empty;
private void button6_Click(object sender, EventArgs e)
    {
        string x = //some varying value I get from other parts of my program
        if(x!=last)
        {
            listBox1.Items.Clear();
            listBox1.Items.Add(x + /*other things*/);
            last = x;
        }
    }

If this string is super important and gets passed around alot, maybe you should wrap it in a class. 如果这个字符串非常重要并且可以传递很多,也许你应该把它包装在一个类中。 The class can hold the string value as a property, but also keep track of when it has changed. 该类可以将字符串值保存为属性,但也可以跟踪它何时更改。

public class StringValue
{
   private bool _changed;
   public string StrValue{get; set{ _changed = true;}
   public bool Changed{get;set;}
}

this is rudimentery of course 这当然是rudimentery

On the page load add the current value to viewstate and at the button click check the current value is equal to the value in the view state. 在页面加载时,将当前值添加到viewstate,然后在按钮单击检查时,当前值等于视图状态中的值。 If both are equal we can say that the value is not changed. 如果两者相等,我们可以说该值不会改变。

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
    ViewState["CurrentValue"] = Your Value;
}
}
protected void btnSubmit_click(object sender, EventArgs e)
{
if (NewValue==  ViewState["CurrentValue"].ToString())
{
    lblmsg.Text = "value is not changed..";
return;
}
else
    lblmsg.Text = "value is changed..";
}

You can check the detailed article in this link. 您可以查看此链接中的详细文章。

Check Control Value is changed or not 检查控制值是否更改

I'm not sure I understand completely, but it sounds like you should be using a property to set String x; 我不确定我完全理解,但听起来你应该使用属性来设置String x;

string _x = string.Empty;
public string X
{
   set
   {
      if(value != this._x)
      {
         DoFancyListBoxWork();
         this._x = value;
      }
   }

   get
   {
      return this._x;
   }
}

If this is web application, store your last value into session variable. 如果这是Web应用程序,请将您的最后一个值存储到会话变量中。 If this is windows application, store it at a class level variable or in singleton class and use this last value for comparison with new value. 如果这是Windows应用程序,则将其存储在类级变量或单例类中,并使用此最后一个值与新值进行比较。

First, I'd like to ask you to check most of the other answers. 首先,我想请你检查大多数其他答案。 They are more complete, in that they treat more global issues of tracking the changes of a variable. 它们更完整,因为它们处理跟踪变量变化的更多全局问题。

Now, I'm assuming, from reading the snippet of code you provided, that you need to track if a string was changed by the user. 现在,我假设,通过阅读您提供的代码片段,您需要跟踪用户是否更改了字符串 So, in other words, you probably have a TextBox or other kind of control through which the user can change that value. 换句话说,您可能有一个TextBox或其他类型的控件,用户可以通过它来更改该值。 This is where you should focus your attention: just consume the TextChanged event. 这是您应该集中注意力的地方:只需使用TextChanged事件。

If, however, I'm mistaken and your string comes from any other kind of external source, either use the wrapper class suggested by @Ryan Bennett or, if you are using .Net 4, use a dynamic container, which raises a PropertyChanged event whenever any property is changed. 但是,如果我错了,你的字符串来自任何其他类型的外部源,要么使用@Ryan Bennett建议的包装类,要么使用.Net 4,使用动态容器,它会引发PropertyChanged事件任何财产改变时。

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

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