如何在c#类上设置变量时保留旧值
本文关键字:变量 保留 设置 | 更新日期: 2023-09-27 18:10:22
我想创建一个可以设置多个值的类,而不是删除已经设置的旧值,而是添加它和旧值。这是我的样品。
myClass myCls = new myClass();
myCls.setString = "My first string!";
myCls.setString = "My second string!";
myCls.setString = "My third string!";
string printMe = myCls.getString();
Console.WriteLine(printMe);
当它输出类似;
//My first string!My second string!My third string!
一种方法是在myClass
中添加一个新属性public class myClass
{
private string _setString;
public string setString
{
get
{
return _setString;
}
set
{
AuditTrail += value;
_setString = value;
}
}
public string AuditTrail{get;set;}
}
然后在主方法中输入:
Console.WriteLine(AuditTrail);
你可以试试这个类:
public class ValueKeeper {
private List<object> values;
public object Value {
get { return ToString(); }
set { values.Add(value); }
}
public ValueKeeper() {
values = new ArrayList<object>();
}
public override string ToString() {
string result = String.Empty;
foreach(object value in values) result += value.ToString();
return result;
}
}
当然可以改进,但它会满足你的需要。
ValueKeeper valueKeeper = new ValueKeeper();
valueKeeper.Value = 1;
valueKeeper.Value = "This is a string";
valueKeeper.Value = someCustomObject;
string str = valueKeeper.Value;
Console.WriteLine(str); //PRINTS OUT "1This is a stringxxxxx"
//Where "xxxx" is the string representation of the custom object
ValueKeeper valueKeeper = new ValueKeeper();
valueKeeper.Value = 1;
valueKeeper.Value = "This is a string";
valueKeeper.Value = someCustomObject;
string str = valueKeeper.Value;
Console.WriteLine(str); //PRINTS OUT "1This is a stringxxxxx"
//Where "xxxx" is the string representation of the custom object
您可以创建这样的类。
class MyClass
{
private string myString;
public string MyString
{
get
{
return myString;
}
set
{
myString += value;
}
}
}
在你的程序中你可以这样使用
MyClass c = new MyClass();
c.MyString = "String 1";
c.MyString = "String 2";
Console.WriteLine(c.MyString);
这似乎是一个奇怪的请求,但它可以做到!
class myClass
{
//Properties
private string privateString;
//Constructor
public myClass()
{
}
//Methods
public void setString(string val)
{
privateString += val;
}
public string getString()
{
return privateString;
}
}
string _entry;
public string Entry
{
get { return _entry; }
set { _entry += value; }
}