强制类使用构造函数

时间:2015-06-23 17:49:00

标签: c# class constructor

我有以下课程

class MyClass
{
    string _val1 = null;
    string _val2 = null;
    string _val3 = null;

    public string Val1{get;set;}
    public string Val2{get;set;}
    public string Val3{get;set;}

    public MyClass(){}
    public MyClass(string val_id1, string val_id2 = null, string val_id3 = null)
    {
        //do some stuff.. set _val1,_val2,_val3
    }
}

我的意图是允许使用以下任一方法实例化它。

//using parameterized constructor
MyClass TestMyClass1 = new MyClass("v1");
MyClass TestMyClass1 = new MyClass("v1","v2");

//using default constructor and setting values
MyClass TestMyClass2 = new MyClass();
TestMyClass.Val1 = "my_test_value1";
TestMyClass.Val2 = "my_test_value2";
TestMyClass.Val3 = "my_test_value3";

这似乎运行得很好,但是当使用默认构造函数显式设置值然后为对象分配显式值时,我需要强制某些逻辑。例如,即使有人说TestMyClass.Val1 = "my_test_value1",我也需要在参数化构造函数中使用逻辑。

因此,如果显式设置Val1,则应使用//do some stuff.. set _val1,_val2,_val3代码块来填充对象。这样做的正确方法是什么?

2 个答案:

答案 0 :(得分:3)

将两种情况下需要调用的逻辑移动到私有方法,例如

class MyClass
{

    private void InitializeStuff()
    {
        //do some stuff.. set _val1,_val2,_val3
    }

    string _val1 = null;

    public string Val1
    {
        get { return _val1; } 
        set 
        {
           InitializeStuff();
           _val1 = value; // Unless InitializeStuff sets this, in which case pass value in to it.
        }
    }  

    public MyClass()
    {
        // If needed:
        InitializeStuff();
    }

    public MyClass(string val_id1, string val_id2 = null, string val_id3 = null)
    {
        InitializeStuff();
    }
}

答案 1 :(得分:0)

//do some stuff.. set _val1,_val2,_val3移到相应的设置器中。

class MyClass
{
    string _val1 = null;
    string _val2 = null;
    string _val3 = null;

    public string Val1
    {
        get
        {
            return _val1;
        }
        set
        {
            // do some stuff with _val1
            _val1 = value;
        }
    }

    public string Val2
    {
        get
        {
            return _val2;
        }
        set
        {
            // do some stuff with _val2
            _val2 = value;
        }
    }

    public string Val3
    {
        get
        {
            return _val3;
        }
        set
        {
            // do some stuff with _val3
            _val3 = value;
        }
    }

    public MyClass(){}
    public MyClass(string val_id1, string val_id2 = null, string val_id3 = null)
    {
        // Don't set _valX instead set ValX
    }
}