这是测试类
public class Test
{
public string mystr;
}我从方法上称之为:
string my = "ABC";
Test test = new Test();
test.mystr = my;
test.mystr = "";以上位代码的结果是:my = "ABC"和test.mystr = ""
如何在更改my时将test.mystr = ""设置为空字符串test.mystr = ""
发布于 2013-05-09 11:47:15
如果我正确理解,您希望将变量my和test.myStr链接起来,那么如果一个变量发生了变化,那么另一个变量呢?
答案很简单:它不能!
字符串是一个不可变的类。多个引用可以指向一个字符串实例,但是一旦修改了这个实例,就会用新的值创建一个字符串实例。因此,一个新的引用分配给一个变量,而其他变量仍然指向其他实例。
有一个解决办法,但我怀疑你不会对此感到满意:
public class Test
{
public string mystr;
}
Test myTest1 = new Test { myStr = "Hello" };
Test myTest2 = myTest1;现在,如果您更改myTest1.myStr,变量myTest2.myStr也将被修改,但这只是因为myTest1和myTest2是相同的实例。
还有其他类似的解决方案,但都可以归结为相同的方面:一个类包含对字符串的引用。
发布于 2013-05-09 11:47:57
.NET中的字符串是不可变的,不像那样工作。您可以尝试的一种方法是对字符串使用可变的包装器。
public class StringReference
{
public string Value {get; set;}
public StringReference(string value)
{
Value = value;
}
}
public class Test
{
internal StringReference mystr;
}
StringReference my = new StringReference("ABC");
Test test = new Test();
test.mystr = my;
test.mystr.Value = "";
// my.Value is now "" as well发布于 2013-05-09 11:48:34
string my = "ABC";
Test test = new Test();请注意,您的Test类与字符串my之间没有关系。我不完全确定你想实现什么,但我们可以这样做:
public class Test
{
private string _mystr;
private Action<string> _action;
public Test(Action<string> action)
{
_action = action;
}
// Let's make mystr a property
public string mystr
{
get { return _mystr; }
set
{
_mystr = value;
_action(_mystr);
}
}
}现在你可以这样做了:
string my = "ABC";
Test test = new Test((mystr) => { if(string.IsNullOrEmpty(mystr)) my = ""; });
test.mystr = my;
test.mystr = "";https://stackoverflow.com/questions/16460962
复制相似问题