class Program
{
static void Main(string[] args)
{
Console.WriteLine(SomeFunction<int>()==null);
var temp = new SomeClass<int>();
Console.WriteLine(temp.SomeFunction() == null);
Console.ReadKey();
}
static public T? SomeFunction<T>() where T : struct
{
return null;
}
public class SomeClass<T> where T : struct
{
public T? SomeFunction()
{
return null;
}
}
}
In the above example, why does a nullable type need the struct constraint?
I don't understand why struct is the right syntax and not object or class.
Because Nullable<T>
(or T?
) also restricts T
to be a struct.
So, for SomeFunction<T>
's generic type parameter T
to fulfill Nullable<T>
's requirements, SomeFunction<T>
must also declare the same constraints.
Here's another example of how constraints must be propagated :
interface ISomeInterface { }
class MyClass<T> where T: ISomeInterface { }
class Program
{
//MyClass's constaints must be "re-declared" here
public MyClass<T> SomeFunction<T>() where T : ISomeInterface
{
}
}
And why does Nullable<T>
do that? Because a nullable reference type would make no sense. Refence types are already nullable.
T?
is shorthand for Nullable<T>
and Nullable<T>
requires that T
be a struct:
public struct Nullable<T> where T : struct
Nullable<T>
is a struct (see MSDN ) however it is the only struct that does not satisfy the struct constraint. On a side note you cannot use a Nullable as a generic type parameter when either the class or struct constraints is used.
The basic idea of Nullable<T>
is to have a storage location that can contain T or can represent "the value is missing"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.