c#中的基本/非空类型名
本文关键字:类型 | 更新日期: 2023-09-27 18:13:23
c#中的基本类型名是什么?是的,我们有一个类似的答案,但只提到类型,而不是类型名:https://stackoverflow.com/a/13530321/3691653
。它提到了System.Int32
和System.Single
等类型,但没有提到类型名int
和float
,它们也可以为我编译。那么,包含别名的完整类型名列表是什么呢?
换句话说,我对需要Nullable<>关键字才能设置为空的非空typenames/typenames感兴趣。
像这样:
alias type (in System namespace)
byte Byte
sbyte SByte
short Int16
ushort UInt16
int Int32
uint UInt32
long Int64
ulong UInt64
decimal Decimal
float Single
double Double
请参阅https://msdn.microsoft.com/en-us/library/ya5y69ds.aspx
需要Nullable<>
的基本类型和类型名是两个完全不同的东西。
任何声明为struct
而不是class
的东西都是不可空的,并且需要将Nullable<>
包裹在它周围以设置为空。
"完整列表"是不可能的,因为任何人都可以编写自己的结构体。
如果你只想知道给定的Type是否可以包装成Nullable<>或者不是,那么就相当于询问它是否是值类型:
Type someType = typeof(int); // then, try to change this to "typeof(string)"
Type someTypeNullable = null;
if (someType.IsValueType)
{
someTypeNullable = typeof(Nullable<>).MakeGenericType(someType);
}
if (someTypeNullable != null)
{
Console.WriteLine("nullable version: " + someType + "?");
}
else
{
Console.WriteLine(someType + " is a reference type");
}