gpt4 book ai didi

c# - 给定一个类型,你如何确定它被装箱的类型?

转载 作者:行者123 更新时间:2023-12-04 10:56:04 25 4
gpt4 key购买 nike

documentation :

When a nullable type is boxed, the common language runtime automatically boxes the underlying value of the Nullable object, not the Nullable object itself...



在代码中:
public Type GetBoxedType(Type type)
{
Type result;

if (Nullable.GetUnderlyingType(type) != null)
{
result = Nullable.GetUnderlyingType(type);
}
else
{
throw new NotImplementedException();
}

return result;
}

我如何将这种方法推广到所有封闭类型?

最佳答案

如果我正确理解您的要求,这就是您想要的:

Type GetBoxedType(Type type)
{
var underlyingType = Nullable.GetUnderlyingType(type);
return underlyingType ?? type;
}

对于引用类型,它返回相同的类型(即对于 List<string>,它将返回 List<string>,因为引用类型没有装箱)。
对于 Nullable<T> 以外的值类型它也将返回相同的类型(例如 int 表示 int ),因为这就是它们的装箱方式。
而对于 Nullable<T>它将返回 T就像你已经实现了。

关于c# - 给定一个类型,你如何确定它被装箱的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59180389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com