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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13497626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 16:44:06  来源:igfitidea点击:

How to return a value using constructor in c#?

.netconstructor

提问by Sanmuga Nathan

I follow a convention that I won't use any print statements in classes, but I have done a parameter validation in a constructor. Please tell me how to return that validation which I've done in the constructor to the Main function.

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

回答by Oded

The constructor does return a value - the type being constructed...

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

A constructor is not supposed to return any other type of value.

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

When you validate in a constructor, you should throw exceptionsif the passed in values are invalid.

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

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

回答by Adil

Constructors do not have a return type, but you can pass values by reference using the refkeyword. It would be better to throw an exception from the constructor to indicate a validation failure.

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

回答by nVn

Make a Constructor with Out parameter and send your return value via same.

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

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

回答by Pawel Czapski

I think my approach might be useful also. Need to add public property to constructor, then you can access this property form other class, as in below example.

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

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

回答by Adi Lester

When a constructor receives an invalid argument, it's common to throw an exception. You can then catch this exception and parse the data it contains.

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

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

回答by Jon B

A constructor returns the type being instantiated, and, if necessary, can throw an exception. Perhaps a better solution would be to add a static method to trycreating an instance of your class:

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

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