new constraint (C# Reference)
The new
constraint specifies that a type argument in a generic class or method declaration must have a public parameterless constructor. To use the new
constraint, the type cannot be abstract.
Apply the new
constraint to a type parameter when a generic class creates new instances of the type, as shown in the following example:
class ItemFactory<T> where T : new()
{
public T GetNewItem()
{
return new T();
}
}
When you use the new()
constraint with other constraints, it must be specified last:
public class ItemFactory2<T>
where T : IComparable, new()
{ }
For more information, see Constraints on Type Parameters.
You can also use the new
keyword to create an instance of a type or as a member declaration modifier.
C# language specification
For more information, see the Type parameter constraints section of the C# language specification.
See also
Phản hồi
https://aka.ms/ContentUserFeedback.
Sắp ra mắt: Trong năm 2024, chúng tôi sẽ dần gỡ bỏ Sự cố với GitHub dưới dạng cơ chế phản hồi cho nội dung và thay thế bằng hệ thống phản hồi mới. Để biết thêm thông tin, hãy xem:Gửi và xem ý kiến phản hồi dành cho