C# 属性 -0020

属性(Property),是一个方法或一对方法,在客户端(使用者)代码来看,它们就是一个字段。

属性的原始定义:

class PhoneCustomer
{
	private string _firstName;
	public string FirstName
	{
		get
		{
			return _firstName;
		}
		set
		{
			_firstName = value;
		}
	}
	//...
}

上面这种比较原始,比较麻烦,现在一般都不这么写,除非需要在get 或set里面做些额外的逻辑。

现在一般的写法(自动实现的属性):

public string FirstName {get; set;}

也可以初始化:

public string FirstName {get; set;} = "Richie"

带访问修饰符的写法:

public string FirstName {get; private set;}

表达式体属性

C#6开始,只有get访问器的属性可以使用表达式体属性。

public class Person
{
	public Person(string firstName, string lastName)
	{
		FirstName = firstName;
		LastName = lastName;
	}
	public string FirstName { get; }
	public string LastName { get; }
	public string FullName => $"{FirstName} {LastName}";
}
    class Customer
    {
        public static string Type { get; set; }
        public int CustomerId { get; set; }
        public string Name { get; set; }

        public string GetFullInformation() => $"{CustomerId} - {Name}";

        public string FullName => $"{CustomerId} - {Name}";

        public static string GetStaticFormatedType()
        {
            return $"Customer Type: {Type}";
        }
    }
原文地址:https://www.cnblogs.com/codesee/p/13111861.html