简体   繁体   中英

C# Constructor parameter passing

I currently restruct my program to be more object-orientated and I'm having trouble with the constructors of my objects.

All objects are stored in a database which has to be human-readable, so I figured it would be nice for the programmer to pass the constructor of an object the table or datarow directly and the object would get the values itself.

So, what I wanted to do was this:

public TestObject(Data.MyDataTable table) {
 // Some checks if the table is valid
 TestObject(table[0]);
}

public TestObject(Data.MyDataRow row) {
 // Some checks if the row is valid
 TestObject(row.Name, row.Value);
}

public TestObject(String name, String value) {
 // Some checks if the strings are valid
 _name = name;
 _value = value;
}

So, as you see, I want sort of a "constructor chain" that, depending on how the programmer calls it, the values are passed through and validated in each step. I tried it the way I wrote it, but it didn't work.

Error 'TestObject' is a 'type' but is used like a 'variable'

I also tried writing this.TestObject(...) but no changes.

Error 'TestObject' does not contain a definition for 'TestObject' and
no extension method 'TestObject' accepting a first argument of type
'TestObject' could be found

How can I go about this?

You chain constructors like this:

public TestObject(Data.MyDataTable table) : this(table[0])
{

}

public TestObject(Data.MyDataRow row) : this(row.Name, row.Value)
{

}

public TestObject(String name, String value) 
{
 // Some checks if the strings are valid
 _name = name;
 _value = value;
}

Note: the use of the this keyword to indicate the current object, use of the parameters that are passed in to one constructor to the chained constructor.

Constructor chaining works like that :

public TestObject(Data.MyDataTable table) : this(table[0])
{

}

public TestObject(Data.MyDataRow row) : this(row.Name, row.Value)
{

}

public TestObject(String name, String value)
{
 // Some checks if the strings are valid
 _name = name;
 _value = value;
}

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