在c#类上设置变量时如何保留旧值

时间:2014-06-26 19:08:05

标签: c#

我想创建一个可以设置多个值的类,而不是删除已经设置的旧值,而是添加它和旧值。这是我的样本。

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!

5 个答案:

答案 0 :(得分:1)

您可以尝试使用此课程:

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

答案 1 :(得分:1)

一种方法是在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);

答案 2 :(得分:0)

string _entry;
public string Entry
{
    get { return _entry; }
    set { _entry += value; }
}

答案 3 :(得分:0)

您可以像这样创建类。

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

答案 4 :(得分:0)

这似乎是一个奇怪的请求,但它可以做到!

 class myClass
    {
        //Properties
        private string privateString;

        //Constructor
        public myClass()
        {

        }

        //Methods
        public void setString(string val)
        {
            privateString += val;
        }

        public string getString()
        {
            return privateString;
        }

    }