从调用另一个构造一个构造函数在同一个班 [英] Calling a constructor from another constructor in the same class

查看:196
本文介绍了从调用另一个构造一个构造函数在同一个班的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一类有两个构造函数(C#)。这里是code片断:

 公共类FooBar的()
{
    公共FooBar的(字符串s)
    {
        //构造1,一些功能
    }

    公共FooBar的(int i)以:这(我的字符串)
    {
        //构造函数2,其他一些功能
    }

}
 

是的,我知道,我可以从另一个使用上述方法调用一个构造函数。但在这种情况下,如果我叫构造2,构造1中的所有语句将运行很语句之前在构造函数中2执行。

我要的是,在构造函数中2的所有语句运行后,然后它会调用构造函数1。

在我确切的情况,我所做的用户身份验证。构造1只用用户ID检索用户信息,但使用电子邮件和密码构造2确实用户验证。如果用户是在数据库中,它得到了用户ID,现在我想构造1填充类的所有属性。

请让我们,如果你需要更多的信息,我知道。如果你认为还有另一种更好的方法,我会很乐意听的建议。

更新1: 我不知道为什么这样的事情是不实现的:

 公共FooBar的(布尔B)
{
    //构造函数3,多了一些功能
    this.FooBar(我的字符串); //调用构造函数1
}
 

解决方案

在这种情况下,只是不使用构造函数调用,但是这样的:

 公共类FooBar的()
{
    公共FooBar的(字符串s)
    {
        INIT1();
    }

    公共FooBar的(int i)以
    {
        INIT2();
        INIT1();
    }

}
 

在哪里我假定 INIT1(..) INIT2(..)是涉及到一些具体的方法相应的构造intialization逻辑。

其实你可以安排最适合您需要的方式这个函数调用。

I have a class with two constructors (C#). Here is the code snippet:

public class FooBar()
{
    public FooBar(string s)
    {
        // constructor 1, some functionality
    }

    public FooBar(int i) : this("My String")
    {
        // constructor 2, some other functionality
    }

}

Yes, I know that I can call one constructor from another using the above mentioned approach. But in this scenario, if I call constructor 2, all statements in constructor 1 will run BEFORE the very statement in constructor 2 is executed.

What I want is that after all statements in constructor 2 are run, then it will call constructor 1.

In my exact situation, I am doing user authentication. Constructor 1 retrieves user information with just the user ID, but constructor 2 does the user authentication using email and password. If a user is in the database, it gets the user ID and now I want constructor 1 to populate all properties of the class.

Please let me know if you require additional information. If you think that there is another better approach, I would be happy to listen the suggestion.

UPDATE 1: I wonder why something like this is not implemented:

public FooBar(bool b)
{
    // constructor 3, some more functionality
    this.FooBar("My String"); // calling constructor 1
}

解决方案

In this case just do not use constructor calls, but something like :

public class FooBar()
{
    public FooBar(string s)
    {
        Init1();
    }

    public FooBar(int i)
    {
        Init2(); 
        Init1();
    }

}

Where I supposed that Init1(..) and Init2(..) are methods related to some specific intialization logic of corresponding constructor.

Actually you can arrange this function calls in a way that better fits your needs.

这篇关于从调用另一个构造一个构造函数在同一个班的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆