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

只有当特定字符串从其先前值更改时,我才能通过按钮单击(将值添加到列表框)来执行操作。 我该如何管理? 以下是我的代码示例:

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*/); } 

单击button6时,我有时可以从前一个值获得与string x相同的值。 在这种情况下,我不希望listBox1添加项(字符串x)。 如何在字符串值更改时添加到列表框? 没有办法预先确定string x 。 它在程序运行时获得价值。

注意:每次向listBox1添加值,之后删除重复项在我的程序中不起作用。

您是否考虑在私有字段中保留字符串值的副本,并简单地将新值与旧值进行比较以查看它们是否匹配?

例如:

 // 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; } 

编辑:正如其他答案所示,当然还有其他更复杂的解决方案,比如封装对属性中字符串值的所有访问,或者将字符串包装在自定义类中。 其中一些替代方案有可能成为“更清洁”,更加面向对象的方法。 但它们比简单地保存字段中的先前值更复杂。 由您来决定您的特定用例是否适合复杂的解决方案,或者更简单的解决方案。 考虑长期可维护性,而不是现在更容易实现。

 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; } } 

如果这个字符串非常重要并且可以传递很多,也许你应该把它包装在一个类中。 该类可以将字符串值保存为属性,但也可以跟踪它何时更改。

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

这当然是rudimentery

我不确定我完全理解,但听起来你应该使用属性来设置String x;

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

如果这是Web应用程序,请将您的最后一个值存储到会话变量中。 如果这是Windows应用程序,则将其存储在类级变量或单例类中,并使用此最后一个值与新值进行比较。

在页面加载时,将当前值添加到viewstate,然后在按钮单击检查时,当前值等于视图状态中的值。 如果两者相等,我们可以说该值不会改变。

 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.."; } 

您可以查看此链接中的详细文章。

检查控制值是否更改

首先,我想请你检查大多数其他答案。 它们更完整,因为它们处理跟踪变量变化的更多全局问题。

现在,我假设,通过阅读您提供的代码片段,您需要跟踪用户是否更改了字符串 换句话说,您可能有一个TextBox或其他类型的控件,用户可以通过它来更改该值。 这是您应该集中注意力的地方:只需使用TextChanged事件。

但是,如果我错了,你的字符串来自任何其他类型的外部源,要么使用@Ryan Bennett建议的包装类,要么使用.Net 4,使用动态容器,它会引发PropertyChanged事件每当任何财产被改变时。