当前位置: 移动技术网 > IT编程>开发语言>c# > 举例讲解C#中自动实现的属性

举例讲解C#中自动实现的属性

2019年07月18日  | 移动技术网IT编程  | 我要评论

探险道修改器,西安网,禁锢之厅

在 c# 3.0 及更高版本,当属性访问器中不需要任何其他逻辑时,自动实现的属性会使属性声明更加简洁。它们还允许客户端代码创建对象。当你声明以下示例中所示的属性时,编译器将创建仅可以通过该属性的 get 和 set 访问器访问的专用、匿名支持字段。
下列示例演示一个简单的类,它具有某些自动实现的属性:

// this class is mutable. its data can be modified from
// outside the class.
class customer
{
  // auto-impl properties for trivial get and set
  public double totalpurchases { get; set; }
  public string name { get; set; }
  public int customerid { get; set; }

  // constructor
  public customer(double purchases, string name, int id)
  {
    totalpurchases = purchases;
    name = name;
    customerid = id;
  }
  // methods
  public string getcontactinfo() {return "contactinfo";}
  public string gettransactionhistory() {return "history";}

  // .. additional methods, events, etc.
}

class program
{
  static void main()
  {
    // intialize a new object.
    customer cust1 = new customer ( 4987.63, "northwind",90108 );

    //modify a property
    cust1.totalpurchases += 499.99;
  }
}

在 c# 6 和更高版本中,你可以像字段一样初始化自动实现属性:

public string firstname { get; set; } = "jane";

上一示例中所示的类是可变的。创建客户端代码后可以用于更改对象中的值。在包含重要行为(方法)以及数据的复杂类中,通常有必要具有公共属性。但是,对于较小类或仅封装一组值(数据)且只有很少行为或没有行为的结构,则应该通过声明 set 访问器为 专用(对使用者的不可变)或通过声明仅一个 get 访问器 (除构造函数外都不可变),使对象不可变。
动实现的属性上允许使用特性,但很明显支持字段上不允许,因为不能从你的源代码访问它们。如果必须使用属性的支持字段上的特性,只需创建一个常规属性。

使用自动实现的属性实现轻量类
本示例演示如何创建一个仅用于封装一组自动实现的属性的不可变轻型类。 当你必须使用引用类型语义时,请使用此种构造而不是结构。
可通过两种方法来实现不可变的属性。 可以将 set 取值函数声明为 private。 属性只能在该类型中设置,但它对于使用者是不可变的。 也可以仅声明 get 取值函数,使属性除了能在该类型的构造函数中设置,在其他任何位置都不可变。
当你声明一个 private set 取值函数时,你无法使用对象初始值设定项来初始化属性。 你必须使用构造函数或工厂方法。
示例
下面的示例演示了实现具有自动实现属性的不可变类的两种方法。 这两种方法均使用 private set 声明其中一个属性,使用单独的 get 声明另一个属性。 第一个类仅使用构造函数来初始化属性,第二个类则使用可调用构造函数的静态工厂方法。

// this class is immutable. after an object is created, 
  // it cannot be modified from outside the class. it uses a 
  // constructor to initialize its properties. 
  class contact
  {
    // read-only properties. 
    public string name { get; }
    public string address { get; private set; }

    // public constructor. 
    public contact(string contactname, string contactaddress)
    {
      name = contactname;
      address = contactaddress;        
    }
  }

  // this class is immutable. after an object is created, 
  // it cannot be modified from outside the class. it uses a 
  // static method and private constructor to initialize its properties.  
  public class contact2
  {
    // read-only properties. 
    public string name { get; private set; }
    public string address { get; }

    // private constructor. 
    private contact2(string contactname, string contactaddress)
    {
      name = contactname;
      address = contactaddress;        
    }

    // public factory method. 
    public static contact2 createcontact(string name, string address)
    {
      return new contact2(name, address);
    }
  }

  public class program
  { 
    static void main()
    {
      // some simple data sources. 
      string[] names = {"terry adams","fadi fakhouri", "hanying feng", 
               "cesar garcia", "debra garcia"};
      string[] addresses = {"123 main st.", "345 cypress ave.", "678 1st ave",
                 "12 108th st.", "89 e. 42nd st."};

      // simple query to demonstrate object creation in select clause. 
      // create contact objects by using a constructor. 
      var query1 = from i in enumerable.range(0, 5)
            select new contact(names[i], addresses[i]);

      // list elements cannot be modified by client code. 
      var list = query1.tolist();
      foreach (var contact in list)
      {
        console.writeline("{0}, {1}", contact.name, contact.address);
      }

      // create contact2 objects by using a static factory method. 
      var query2 = from i in enumerable.range(0, 5)
             select contact2.createcontact(names[i], addresses[i]);

      // console output is identical to query1. 
      var list2 = query2.tolist();

      // list elements cannot be modified by client code. 
      // cs0272: 
      // list2[0].name = "eugene zabokritski"; 

      // keep the console open in debug mode.
      console.writeline("press any key to exit.");
      console.readkey();        
    }
  }

输出:

  terry adams, 123 main st.
  fadi fakhouri, 345 cypress ave.
  hanying feng, 678 1st ave
  cesar garcia, 12 108th st.
  debra garcia, 89 e. 42nd st.

编译器为每个自动实现的属性创建了支持字段。 这些字段无法直接从源代码进行访问。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网