Visual Studio Shortcu/Syntax for fast property assignment
Say Suppose you have a class
public class Person
{
public int PesronId{get;set;}
public string FirstName{get;set;}
public string LastName{get;set;}
public string Gender{get;set;}
}
Now We create an object p1
Person p1 = new Person();
Next w开发者_C百科e have values from textboxes to be assigned to p1 eg.
p1.PersonId = textbox1.text;
p1.FirstName = textbox2.text;
p1.LastName = textbox3.text;
Is there a more efficient way of doing this in Visual Studio 2010, by which I will get something like this
p1.PersonId =
p1.FirstName =
p1.LastName =
so that I dont have to manually type the properties for p1.
Or is then an alternate syntax that I can use.
There's simpler syntax for the code:
Person p1 = new Person
{
PersonId = textbox1.Text,
FirstName = textbox2.Text,
LastName = textbox3.Text
};
This is object initializer syntax, introduced in C# 3.
I think I'd misread the question though - it sounds like you're just interested in cutting down the typing required. There may be something which will do that, but personally I find IntelliSense is fine on its own. The readability of the code afterwards is much more important than the time spent typing, IMO.
You might also want to add a constructor to Person to take all the relevant property values - that would simplify things too, and with C# 4's named argument support, you can retain readability.
You can use the new initialization functionality in C#:
Person p1 = new Person()
{
PersonId = textbox1.text,
FirstName = textbox2.text,
LastName = textbox3.text
};
精彩评论