简体   繁体   English

C#自动实现的属性-使用内部类

[英]C# Auto-Implemented Properties - Using Inside Class

I'm looking for advice on best practices when using Auto-Implemented Properties. 我在使用自动实现的属性时寻求有关最佳做法的建议。

I always use them if I don't need to refer to the property inside the class. 如果不需要引用类中的属性,则始终使用它们。 However, I'm in the habit of manually adding the private property if I do need to access the property inside the class. 但是,如果我确实需要在类内部访问该属性,则习惯于手动添加私有属性。

For example, if I had a class named Person with firstName and lastName properties and I never had to manipulate that data inside the class I would just do this: 例如,如果我有一个名为Person的类,具有firstName和lastName属性,而不必在类内处理该数据,则可以这样做:

public class Person
{
    public string firstName { get; set; }
    public string lastName { get; set; }
}

However, if I needed to do something with those properties I do this: 但是,如果我需要对这些属性进行操作,请执行以下操作:

public class Person
{
    private string _firstName;
    public string firstName
    {
        get { return _firstName; }
        set { _firstName = value; }
    }

    private string _lastName;
    public string lastName
    {
        get { return _lastName; }
        set { _lastName = value; }
    }

    public void testMethod()
    {
        Debug.Print(_firstName + " " + _lastName);
    }

}

My question: Is this good practice? 我的问题:这是好习惯吗?

No, it's pointless. 不,没有意义。 You should move to fully implemented properties when you need to do more than just setting/getting a backing field. 当您需要做的不仅仅是设置/获取支持字段时,您应该转到完全实现的属性。

As things stand: 就目前情况而言:

Debug.Print(FirstName + " " + LastName); //convention says use UpperCamel for props

would be absolutely fine and introducing a backing-field just introduces unnecessary noise to your code. 绝对没问题,引入后备字段只会给代码带来不必要的干扰。

If, instead, you want to do some validation: 相反,如果您想进行一些验证:

public string LastName
{
    get { return _lastName; }
    set { 
        if(value.Contains("!")){
            throw new Exception("names can't contain '!'");
        }
        _lastName = value; }
}

Now you have a valid reason to move away from auto-implemented properties. 现在,您有充分的理由放弃自动实现的属性。

If you are simply trying to avoid the overhead of a second lookup, don't worry about it. 如果您只是想避免第二次查找的开销,请不必担心。 Chances are that this will never cause performance issues, and if it does, you'll find out through measuring code timings. 很有可能这将永远不会导致性能问题,如果确实如此,您将通过测量代码时序来找出答案。 Trying to write optimally efficient code at the expense of clarity is a bad goal and leads to crufty code. 试图以牺牲清晰度为代价来编写最佳效率的代码是一个糟糕的目标,并且会导致代码混乱。 Favour clarity every time, and when your program runs slow, you can go back and find out what caused it. 每次都需要提高清晰度,并且当程序运行缓慢时,您可以返回并找出导致它的原因。 Research has established that there's an extremely high chance that it won't be what you expected, so it's not an economical pursuit trying to guess. 研究已经确定,极有可能不会达到您的预期,因此尝试猜测并不是一种经济的追求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM