This post originated from an RSS feed registered with .NET Buzz
by Adrian Florea.
Original Post: L'errore CS0310 e le classi abstract
Feed Title: Web Log di Adrian Florea
Feed URL: /error.aspx?aspxerrorpath=/adrian/Rss.aspx
Feed Description: "You know you've achieved perfection in design, not when you have nothing more to add, but when you have nothing more to take away." Antoine de Saint-Exupery
Il messaggio dell'errore CS0310 (e anche la sua descrizione) secondo me è incompleto, cioè non basta che un tipo abbia un costruttore pubblico senza parametri per poter essere utilizzato come type parameter in un tipo generico con una constructor constraint. Il messaggio dell'errore dice: "The type 'typename' must have a public parameterless constructor in order to use it as parameter 'parameter' in the generic type or method 'generic'".
Controesempio:
abstractclassFoo { public Foo() { } } classBar<T> where T : new() { }
Il tipo Foo ha un costruttore pubblico senza parametri ma l'espressione newBar<Foo>() non compila (error CS0310).
La frase nelle specifiche C# (25.7) invece, "If the where clause for a type parameter includes a constructor constraint (which has the form new()), it is possible to use the new operator to create instances of the type" è più chiara in questo senso.
A proposito di costruttori default per classi abstract: in VB.NET è public, in C# è protected (a mio parere ha più senso che sia protected, come in C#).