Usually we cannot restrict the type parameter Tbased on a private type (type struct). This would be pointless because there is only one type that could fit, and as such there is no need for generics. Thus, restrictions such as:
where T : string
or
where T : DateTime
are illegal for a very good reason.
However, when restricting to another type parameter, this can sometimes happen when this other type parameter is "replaced" with the actual type (which, it happens, is sealed). Consider the class:
abstract class ExampleBase<TFromType>
{
internal abstract void M<TFromMethod>(TFromMethod value) where TFromMethod : TFromType;
}
which is completely innocent. In specification:
class ExampleOne : ExampleBase<string>
{
internal override void M<TFromMethod>(TFromMethod strangeString)
{
var a = string.IsNullOrEmpty(strangeString);
Console.WriteLine(a);
var b = strangeString.Substring(10, 2);
Console.WriteLine(b);
}
}
TFromType string. . , M<>. M<> - : :
var e1 = new ExampleOne();
e1.M("abcdefghijklmnopqrstuvwxyz");
:
False
kl
. , where TFromMethod : string, .
, , TFromType - . , :
class ExampleTwo : ExampleBase<DateTime>
{
internal override void M<TFromMethod>(TFromMethod strangeDate)
{
var e = string.Format(CultureInfo.InvariantCulture, "{0:D}", strangeDate);
Console.WriteLine(e);
var f = object.ReferenceEquals(strangeDate, strangeDate);
Console.WriteLine("Was 'strangeDate' a box? " + f);
}
}
, c d ?. strangeDate TFromMethod, DateTime, , strangeDate a DateTime? , string (class ExampleOne ).
, #.
, d strangeDate.Ad... IntelliSense ( Visual Studio) DateTime, , IntelliSense , d !
, , c d , ExampleTwo ( e f), :
var e2 = new ExampleTwo();
e2.M(new DateTime(2015, 2, 13));
:
Friday, 13 February 2015
Was 'strangeDate' a box? False