我有一个约定,即不在类中使用任何打印语句,但我已经在构造函数中进行了参数验证。请告诉我如何将我在构造函数中完成的验证结果返回到主函数中。
我有一个约定,即不在类中使用任何打印语句,但我已经在构造函数中进行了参数验证。请告诉我如何将我在构造函数中完成的验证结果返回到主函数中。
构造函数确实会返回一个值 - 此值为正在构造的类型...
构造函数不应该返回任何其他类型的值。
当您在构造函数中进行验证时,如果传入的值无效,应该抛出 异常。
public class MyType
{
public MyType(int toValidate)
{
if (toValidate < 0)
{
throw new ArgumentException("toValidate should be positive!");
}
}
}
ref
关键字通过引用传递值。最好从构造函数中抛出异常以指示验证失败。public class YourClass
{
public YourClass(ref string msg)
{
msg = "your message";
}
}
public void CallingMethod()
{
string msg = string.Empty;
YourClass c = new YourClass(ref msg);
}
public class ClassA
{
public ClassA(out bool success)
{
success = true;
}
}
构造函数返回正在实例化的类型,并且如果必要,可以抛出异常。也许更好的解决方案是添加一个静态方法来尝试创建类的实例:
public static bool TryCreatingMyClass(out MyClass result, out string message)
{
// Set the value of result and message, return true if success, false if failure
}
我认为我的方法也可能有用。需要在构造函数中添加公共属性,然后您可以像下面的示例一样从其他类访问此属性。
// constructor
public class DoSomeStuffForm : Form
{
private int _value;
public DoSomeStuffForm
{
InitializeComponent();
// do some calculations
int calcResult = 60;
_value = calcResult;
}
// add public property
public int ValueToReturn
{
get
{
return _value;
}
}
}
// call constructor from other class
public statc void ShowDoSomeStuffForm()
{
int resultFromConstructor;
DoSomeStuffForm newForm = new DoSomeStuffForm()
newForm.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
newForm.ShowDialog();
// now you can access value from constructor
resultFromConstructor = newForm.ValueToReturn;
newForm.Dispose();
}
try
{
int input = -1;
var myClass = new MyClass(input);
}
catch (ArgumentException ex)
{
// Validation failed.
}