如何在C#中使用构造函数返回一个值?

18

我有一个约定,即不在类中使用任何打印语句,但我已经在构造函数中进行了参数验证。请告诉我如何将我在构造函数中完成的验证结果返回到主函数中。

6个回答

35

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

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

当您在构造函数中进行验证时,如果传入的值无效,应该抛出 异常

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

哦,我希望我能够点赞一千次。那种像癌症一样蔓延的宽松验证风格真是让人感到非常疲劳。 - jgauffin
@jgauffin - 你指的是哪种风格? - Oded
例如,在您的领域/业务模型上使用DataAnnotation属性。即允许对象具有无效信息,并依赖于调用代码来确保一切都经过验证和正确。你知道的...违反封装。 - jgauffin
@jgauffin - 我明白了。注释但不检查实际上是否保持不变量。 - Oded

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

6
你“可以”做某事并不意味着你“应该”去做。 - Oded

2
创建一个带有输出参数的构造函数,并通过相同的方式发送返回值。
public class ClassA
{
    public ClassA(out bool success)
    {
        success = true;
    }
}

1
如果到了这个地步,你的类就太脆弱了。 - Chad Crowe

1

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

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

1

我认为我的方法也可能有用。需要在构造函数中添加公共属性,然后您可以像下面的示例一样从其他类访问此属性。

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

0
当构造函数接收到无效参数时,通常会抛出异常。然后您可以捕获此异常并解析其中包含的数据。
try
{
    int input = -1;
    var myClass = new MyClass(input);
}
catch (ArgumentException ex)
{
    // Validation failed.
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接