C# 为什么可空类型必须具有结构约束 类程序 { 静态void Main(字符串[]参数) { Console.WriteLine(SomeFunction()=null); var temp=new SomeClass(); Console.WriteLine(temp.SomeFunction()==null); Console.ReadKey(); } 静态公共T?SomeFunction(),其中T:struct { 返回null; } 公共类SomeClass,其中T:struct { 公共T?SomeFunction() { 返回null; } } }
在上面的示例中,为什么可空类型需要struct约束?C# 为什么可空类型必须具有结构约束 类程序 { 静态void Main(字符串[]参数) { Console.WriteLine(SomeFunction()=null); var temp=new SomeClass(); Console.WriteLine(temp.SomeFunction()==null); Console.ReadKey(); } 静态公共T?SomeFunction(),其中T:struct { 返回null; } 公共类SomeClass,其中T:struct { 公共T?SomeFunction() { 返回null; } } },c#,oop,struct,C#,Oop,Struct,在上面的示例中,为什么可空类型需要struct约束? 我不明白为什么struct是正确的语法,而不是object或class。t?是Nullable的缩写,Nullable要求t是一个struct: class Program { static void Main(string[] args) { Console.WriteLine(SomeFunction<int>()==null); var temp = new SomeClass
我不明白为什么struct是正确的语法,而不是object或class。
t?
是Nullable
的缩写,Nullable
要求t
是一个struct:
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;
}
}
}
public结构可为null,其中T:struct
因为可为空的(或T?
)也将T
限制为结构
因此,对于SomeFunction
的泛型类型参数T
,要满足Nullable
的要求,SomeFunction
还必须声明相同的约束
下面是约束必须如何传播的另一个示例:
接口{}
类MyClass,其中T:ISomeInterface{}
班级计划
{
//MyClass的约束必须在此处“重新声明”
公共MyClass SomeFunction(),其中T:ISomeInterface
{
}
}
为什么Nullable
会这样做?因为可为空的引用类型没有意义。引用类型已经可以为null。可以为null
是一个结构(请参见),但它是唯一不满足结构约束的结构。另一方面,在使用类或结构约束时,不能将Nullable用作泛型类型参数
Nullable
的基本思想是拥有一个存储位置,该存储位置可以包含T,也可以表示“值丢失”+1——引用类型已经可以为null的事实并不能证明这个问题的事实:“为什么struct是正确的语法?”@RoyiNamir第一句解释了这一点。我想OP想知道:为什么他们首先选择struct来refelect nullables…@RoyiNamir我不太明白。。。你是在问“为什么对结构而不是类是空的”@RoyiNamir,你是对的。OP确实只想知道这一点,但我想说原因是因为规范这么说。
public struct Nullable<T> where T : struct
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
{
}
}