使用建筑构件和本地分配有什么区别?

时间:2019-07-03 22:40:59

标签: c#

您好,我正在学习构造函数的用法,我想问一下我下面的两个代码片段之间的主要区别是什么。

我要将_fristname实例分配给我在Human构造中创建的本地变量。

public string _firstName;

public Humans()
        {
            string name = "";
            _firstName = name;
        }

我正在为实例_fristname分配局部变量名称。

public string _firstName;

public Humans()
        {
            string name;
            name = _firstName;
        }

为什么当我使用public access修饰符将名称字符串命名为public

Humans()
        {
            public string name;
            name = _firstName;
        }

该类中的整个代码会出现红色错误行吗?为什么本地var不能在构造函数中获得公共访问修饰符,还从三个代码段中指出了一个不可以。

除了用于将实例创建为类类型的对象的模板之外,我想知道构造函数的主要用途是什么。

1 个答案:

答案 0 :(得分:0)

首先,问题的格式难以阅读。如果格式化正确,这样缩进是正确的,代码不会与文本混合,将会很有帮助。但是我想我明白你的意思了。

// I'm not sure if you just left this out, or if you're missing it in your 
// actual class, but need to declare the class.
public class Humans {
    Humans() {
        // The reason this doesn't work is because it's not a member of the class.
        // you can only use access modifiers on a class member
        public string name;
    }
}

在上面,变量是在构造函数中声明的。如果在构造函数中声明,则它仅存在于构造函数中。离开构造函数后,它就会消失。

如果您想拥有属于该类的公共成员名称,请在该类中声明它。

public class Humans {
    public string name;

    public Humans() {
        name = "Some value here...";
    }
}

在此示例中,Humans对象具有一个属性名称,只要您的人类实例存在,该属性名称就可以访问。

Humans human = new Humans();
string humanName = human.name;

因此,如果我们创建Humans对象的新实例,则可以访问name属性。一旦构造了对象,访问修饰符(如public,private等)便可以控制这些属性的访问。因此,它们仅适用于属于该类的值。在构造函数中声明变量时,该变量属于构造函数,而不是类。因此,当构造函数执行完毕时,构造函数内声明的变量也将完成。但是,如果您在类本身的范围内声明变量,则该变量将与类保持一致。并且由于访问该变量需要您遍历该类的实例,因此可以使用访问修饰符控制该变量的访问。私有意味着只有在类内编写的代码才能访问它,而公共意味着有访问该类实例的任何内容都可以访问它。

因此,就像访问修饰符如何工作的简单示例一样,这是Humans类的示例。

public class Humans {
    // These variables are accessible only by code within this class block.
    private string firstName;
    private string lastName;

    // This constructor is public, so it could be accessed anywhere.
    public Humans(string firstName, string lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    // This function is public, so can be called to get the full name.
    public string getFullName() {
        // the variable fullName only exists in the scope of this function.
        // so there is no point in applying an access modifier.
        string fullName = String.format("{} {}", this.firstName, this.lastName);
        // When we return fullName, we return a copy of the value, and the 
        // original variable gets cleaned up.
        return fullName;
    }

    // Lets say we want to allow updating the name, but we want to verify
    // that the name is valid first. We can make public setters.
    public void setFirstName(String firstName) {
        if (!String.isNullOrWhiteSpace(firstName)) {
            this.firstName = firstName;
        } else {
            throw new InvalidArgumentException("First name cannot be null or empty.")
        }
    }

}