How getter should look

强颜欢笑 提交于 2019-12-12 05:39:18

问题


I have seen this kind of code in c#:

  private int id {get;set;}

but I would only create getter for the field cause if there is get and set for it is the same as public field is the only way is:

public int getId(){return id;}

How to automaticly generate only getters in VS2010


回答1:


What you have implemented is known as an Automatic Property they look like this:

private string Name { get; set; }

Automatic properties merely syntactical sugar and in reality, provide a succinct, quick way to implement this code:

private string _name;
public string Name 
{ 
    get { return _name; } 
    set { _name = value; } 
}

You could disregard automatic properties, using manual proeprties and simply remove the get. Or use automatic properties and make the property's value read only to external members by marking the get with the private access modifier:

public string Name { get; private set; }

The code you say you would usually use, is never really needed in C# because properties, in reality are just methods in disguise and should be used as a better convention:

public int getId(){return id;} //bad



回答2:


Do you mean how do you implement a readonly property? If so try:

public int Id { get; private set;}



回答3:


right click on the field, refactor, encapsulated field




回答4:


No they are not the same. A property compiles to one or two methods bound to a property. E.g.:

public int Foo { get; private set; }

compiles to the IL code that works like this:

private int _foo;
public int Foo { get_Foo = get, set_Foo = set }

public int get_Foo() { return _foo; }
private void set_Foo(int value) { _foo = value; }

In other words: properties are methods, while fields are not. That's why you can do things like:

public int Foo { get { return 0; } }

which compiles to:

public int Foo { get_Foo = get }

public int get_Foo() { return 0;}

update

Okay now I understand your question... the answer is the last part that shows how a getter-only works as well as what it does :-)




回答5:


This is Very Similar:

How to create Autoporpertys

Just tipp prop and than write your Type and press Tab to write your name.




回答6:


I think you want a property that is publicly available, but can only be set by the class. Is it something like this:

 public class Entity
 {
     public void Entity()
     {
         ID = ...;  // Some unique id
     }

     public int ID { get; private set; }
 }

This allows the class Entity to read and write the ID, but other classes can only read the ID.



来源:https://stackoverflow.com/questions/14418612/how-getter-should-look

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!