简体   繁体   中英

How can I know that object is changed totally like obj1 = obj2?

My Language is C#.

obj1.Value = "test";

If object value is changed like this, it is easy to handle. I can put the event code in Name Property Set.

But

Class obj1 = new Class("string1");
obj1  = new Class("string1");

When object is changed by assignment like this, How can I know that and Handle it?

I want to limit Name Length and it is limited by another property "Length".

I have 3 constructors.

Class(string value);
Class(int length);
Class(int length, string value);

And 2 Properties.

.Value
.Length

I made obj1 like this

Class obj1 = new Class(3, "ab")

My problem is this.

obj1 = new Class("abcde")

I want to limit Value length 3 but the length of new Class("abcde") is 5. (It can have different value by coding but in my case length is 5)

How can I solve it?

You can check the length of string in the constructor. If the length exceeds the limit, you can throw a new exception. On the object initiation side, you can use try catch block to check if the object is initiated correctly or not. Example:

class Class
{
    public Class(string string1)
    {
        if(string1.Length > 10)
            throw new Exception("Length Exceeded than limit");
    }
}

class Program
{
    static void Main()
    {
        Class obj;
        try
        {
           obj = new Class("stri");
        }
        catch
        {
           MessageBox.Show("Error");
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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