Shortcut to creating many properties all with default get / set body
Is there some shortcut way of handling multiple properties on a class (say 50 spanning string, int, datetime, etc). They will all have the same simple declaration such as
private int myInt;
public int MyInt
{ get { return myInt; }
set { myInt = value; }
}
private datetime someDate;
public datetime SomeDate
{ get { return someDate; }
set { someDate = value; }
}
The reason, is I have a class that will be "bound" to data entry textbox type fields and such. By just making them "public" doesn't work as it wont bind to a field, but will if it's a property with applicable get/set. I just think it's a pain to go through such efforts when it's the same repetition over and over, and believe there is a shorter / more simplified method. I just don't have another mentor to learn开发者_JAVA技巧 from and know that S/O has plenty to help out.
For the current situation I'm in, requires me to only work with .Net 2.0 max... Some restrictions based on handheld devices not yet capable of running 3.0, 3.5, etc.
In C# 3 or higher, you can use auto-implemented properties:
public int MyInt { get; set; }
In VS2010 & 2008 you can right click on the private field, select Refactor->Encapsulate Field.
You will still have to do it field by field, but it has got some smarts in it (with regards to choosing a publicly viewable name), and you can do it all with no typing.
Follow up: i see that the answer from Josh M shows you the keyboard shortcut to do the same thing.
Instead of using fields use properties to begin with:
public int MyInt { get; set }
public DateTime SomeDate { get; set; }
Try CTRL+R+E while on the field.
See more great shortcuts in this blog post.
I don't think there is any shortcut to create fields (other than manually typing it), though it is possible to create properties for "existing" fields in a class. So, in this case you will have write 50 fields, and then you can ask VS to auto-generate the properties for you. Even better if you have Resharper (i think, alt+insert will do the job).
If you have a list of columns/fields and their type, then you can use CodeDom. And then auto-generate the whole class, with all the fields and properties based on the list of columns you have provided.
You said you're stuck with .NET 2.0. Please note that you can use some C# 3.0 features but still target .NET 2.0 Framework. So as long as you use VS2008 and set the target to .NET 2.0 you can use autoprops (and a few other cool features of C# 3.0). Here is a bunch of links on this topic:
http://weblogs.asp.net/shahar/archive/2008/01/23/use-c-3-features-from-c-2-and-net-2-0-code.aspx
http://www.danielmoth.com/Blog/Using-Extension-Methods-In-Fx-20-Projects.aspx
http://www.developer.com/net/csharp/article.php/3598381/The-New-Lambda-Expressions-Feature-in-C-30.htm
type propfull
then press TAB twice
精彩评论