C#构造函数参数传递 [英] C# Constructor parameter passing
问题描述
所有对象都存储在一个数据库中,该数据库必须是人类可读的,所以我认为这将是很好的程序员直接传递对象的表或数据行的对象的构造函数,对象将获得值本身。
所以,我想做的是这样的:
public TestObject(Data.MyDataTable table){
//有些检查表是否有效
TestObject(table [0]);
}
public TestObject(Data.MyDataRow row){
//有些检查行是否有效
TestObject(row.Name,row.Value);
}
public TestObject(String name,String value){
//有些检查字符串是否有效
_name = name;
_value = value;
}
因此,如你所见,我想要一种构造函数链,取决于程序员如何调用它,值在每个步骤中传递和验证。
错误'TestObject'是一个'类型',但是是一个变量
我也试过写 this.TestObject ...)
但没有更改。
错误'TestObject' TestObject'和
没有扩展方法'TestObject'接受
的第一个参数'TestObject'可以被找到
如何解决这个问题?
构造函数链接的工作原理如下:
public TestObject(Data.MyDataTable table):this(table [0])
{
}
public TestObject row.Name,row.Value)
{
}
public TestObject(String name,String value)
{
//有些检查字符串是否有效
_name = name;
_value = value;
}
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?
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;
}
这篇关于C#构造函数参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!