我正在尝试编写一个代码,在 C# 中输出数字类型 (
int
, uint
, ...) 的详细信息 (MinValue
, MaxValue
, sizeof
, 名称)。
这是我到目前为止编写的代码:
Console.WriteLine(new string('-', 120));
Console.WriteLine("{0,-10} {1,-20} {2,40} {3,40}",
"Type", "Byte(s) of memory", "Min", "Max");
Console.WriteLine(new string('-', 120));
Type[] types = new Type[] {
typeof(byte),
typeof(sbyte),
typeof(int),
typeof(uint),
typeof(short),
typeof(ushort),
typeof(long),
typeof(ulong),
typeof(Int128),
typeof(UInt128),
typeof(Half),
typeof(float),
typeof(double),
typeof(decimal),
};
int[] typesSizes = new int[]
{
sizeof(System.Byte),
sizeof(sbyte),
sizeof(int),
sizeof(uint),
sizeof(short),
sizeof(ushort),
sizeof(long),
sizeof(ulong),
sizeof(Int128),
sizeof(UInt128),
sizeof(Half),
sizeof(float),
sizeof(double),
sizeof(decimal),
};
dynamic instance;
int size;
Type type;
for (int i = 0; i < typesSizes.Length; i++)
{
size = typesSizes[i];
type = types[i];
instance = Activator.CreateInstance(type);
if (instance == null)
{
throw new NullReferenceException();
}
var minValue = type.GetProperty("MinValue")?.GetValue(instance);// here it returns null for built-in types
var maxValue = type.GetProperty("MaxValue")?.GetValue(instance);
Console.WriteLine("{0,-10} {1,-20} {2,40} {3,40}",
type.Name, size, minValue, maxValue);
}
我不知道为什么 - 但它对于内置数字类型返回 null。
我知道只需创建 4 个数组并复制粘贴属性就可以更轻松地解决这个问题。但我想知道为什么/如何发生这种情况
我使用ai来获取答案,但没有成功
您的代码大部分是正确的,但是
MinValue
和 MaxValue
是(常量)字段,而不是属性。
所以一定是
GetField
而不是GetProperty
:
var minValue = type.GetField("MinValue")?.GetValue(instance);
var maxValue = type.GetField("MaxValue")?.GetValue(instance);