Guide to the Language
Download 2 Mb. Pdf ko'rish
|
C sharp
- Bu sahifa navigatsiya:
- Why Use Constraints
Multiple Constraints
Multiple constraints can be applied to a type parameter by specifying them in a comma-separated list. Furthermore, to constrain more than one type parameter, additional where clauses can be added. Note that if either the class or the struct constraint is used, it must appear first in the list. Moreover, if the parameterless constructor constraint is used, it must be the last one in the list. class J where T : class, I where U : I, new() {} Why Use Constraints Aside from restricting the use of a generic method or class to only certain parameter types, another reason for applying constraints is to increase the number of allowed operations and method calls supported by the constraining type. An unconstrained type may only use the System.Object methods. However, by applying a base class constraint, the accessible members of that base class also become available. class Person { public string name; } class PersonNameBox { public string box; public void StorePersonName(T a) Chapter 28 GeneriCs 169 { box = a.name; } } The following example uses the parameterless constructor constraint. This constraint enables new objects of the type parameter to be instantiated. class MyClass Note that if a class has a constraint on its type parameter and a child of that class has a type parameter that’s constrained by the base class, that constraint must also be applied to the child class’s type parameter. class MyChild where T : MyClass Chapter 28 GeneriCs 171 © Mikael Olsson 2020 M. Olsson, C# 8 Quick Syntax Reference, https://doi.org/10.1007/978-1-4842-5577-3_29 Download 2 Mb. Do'stlaringiz bilan baham: |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling