New () explains the constructor constraints of the WHERE clause, any type with a new () constraint must have an accessible parameterless constructor, and normally the class created by C # has a parameterless constructor, even if you do not write it, but if you write a constructor with a parameter, Then there is no default without the argument, you need to manually write a
| The code is as follows |
Copy Code |
<summary>
interface of the nationality
</summary>
public interface Inationality
{
String nationality
{
Set
}
String getnationality ();
} |
The interface of nationality does not change or is this, the class that inherits this interface is slightly modified, adding a construction method for each class, and transforming the following:
| The code is as follows |
Copy Code |
|
<summary>
Chinese
</summary>
public class Chinese:inationality
{
Public Chinese (string defaultnationality)
{
_nationality = defaultnationality;
}
private string _nationality;
public string Nationality
{
Set
{
_nationality = value;
}
}
public string getnationality ()
{
return string. IsNullOrEmpty (_nationality)? "Chinese.": _nationality;
}
}
<summary>
American
</summary>
public class American:inationality
{
Public American (string defaultnationality)
{
_nationality = defaultnationality;
}
private string _nationality;
public string Nationality
{
set {_nationality = value;}
}
public string getnationality ()
{
return string. IsNullOrEmpty (_nationality)? "American.": _nationality;
}
}
|
In fact, the change is not very large, the generic class also did not modify, but will error, in the creation of instantiated objects, as follows:
| code is as follows |
copy code |
|
///<summary>
///
///</summary>
///<typeparam Name = "T" ></typeparam>
public class printnationality<t> where t:inationality, new ()//Because there is a constraint for new (), So when the compiler fails to compile, the new () is removed, or the parameterless constructor of the public type is added to the class that inherits Inationality
{
//t item = new T (); cannot create an instantiated object at this point, prompting the error "must have a non-abstract type with a public parameterless constructor to be used as a parameter T in a generic type or method" xxxx "
public void Print ()
{
// Console.WriteLine (String. Format ("nationality:{0}", item. Getnationality ()));
}
} |
To resolve the problem above, add a parameterless public-type constructor to each class that inherits the Inationality interface, or remove new () after the derived class. In this case, there is no problem when instantiating a generic class