如何在c#中使用构造函数返回值?

时间:2012-11-21 16:26:01

标签: .net constructor

我遵循一个约定,我不会在类中使用任何print语句,但我在构造函数中进行了参数验证。请告诉我如何将我在构造函数中完成的验证返回给Main函数。

6 个答案:

答案 0 :(得分:31)

构造函数确实返回一个值 - 正在构造的类型......

构造函数不应该返回任何其他类型的值。

在构造函数中验证时,如果传入的值无效,则应抛出 exceptions

public class MyType
{
    public MyType(int toValidate)
    {
      if (toValidate < 0)
      {
        throw new ArgumentException("toValidate should be positive!");
      }
    }
}

答案 1 :(得分:4)

构造函数没有返回类型,但您可以使用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);       
}

答案 2 :(得分:2)

使用Out参数创建一个构造函数,并通过它发送返回值。

public class ClassA
{
    public ClassA(out bool success)
    {
        success = true;
    }
}

答案 3 :(得分:0)

当构造函数收到无效参数时,抛出异常是很常见的。然后,您可以捕获此异常并解析它包含的数据。

try
{
    int input = -1;
    var myClass = new MyClass(input);
}
catch (ArgumentException ex)
{
    // Validation failed.
}

答案 4 :(得分:0)

构造函数返回正在实例化的类型,如果需要,可以抛出异常。也许更好的解决方案是添加静态方法尝试创建类的实例:

public static bool TryCreatingMyClass(out MyClass result, out string message)
{
    // Set the value of result and message, return true if success, false if failure
}

答案 5 :(得分:0)

我认为我的方法也可能有用。需要向构造函数添加公共属性,然后可以从其他类访问此属性,如下例所示。

// 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();
}