- 由於 Auto-implemented properties 的用法產生,也連同產生出新的 Object Initializers, Collection Initializers
public class User
{
// Auto-implemented properties.
public string Name { get; set; }
public int Age { get; set; }
}
public class Initializers
{
public void function()
{
User user = new User();
user.Name = "Lyndon";
user.Age = 30;
}
}
public class Initializers
{
public void function()
{
User user = new User() { Name = "Lyndon", Age = 30 };
}
}
Collection Initializers
public class Initializers
{
public void function()
{
List< User> lUser = new List< User>();
lUser.Add( new User { Name = "Helen", Age = 25 } );
lUser.Add( new User { Name = "Lyndon", Age = 30 } );
lUser.Add( new User { Name = "Daisy", Age = 27 } );
}
}
public class Initializers
{
public void function()
{
List< User> lUser = new List< User>()
{
new User { Name = "Helen", Age = 25 },
new User { Name = "Lyndon", Age = 30 },
new User { Name = "Daisy", Age = 27 }
};
}
}
public class Initializers
{
public void function()
{
Dictionary< int, User> students = new Dictionary< int, User>()
{
{ 111, new User { Name = "Helen", Age = 25 }},
{ 112, new User { Name = "Lyndon", Age = 30 }},
{ 113, new User { Name = "Daisy", Age = 27 }}
};
}
}
public class Initializers
{
public void function()
{
List< User> lUser = new List< User>(3)
{
new User { Name = "Helen", Age = 25 },
new User { Name = "Lyndon", Age = 30 },
new User { Name = "Daisy", Age = 27 }
};
}
}
- Ref
- https://weblogs.asp.net/scottgu/new-c-orcas-language-features-automatic-properties-object-initializers-and-collection-initializers
- https://docs.microsoft.com/zh-tw/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers
- https://docs.microsoft.com/zh-tw/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers
沒有留言:
張貼留言