gpt4 book ai didi

c# - Marshal.SizeOf(typeof(T)) 和 Marshal.SizeOf(default(T)) 有什么区别?

转载 作者:太空宇宙 更新时间:2023-11-03 17:38:29 25 4
gpt4 key购买 nike

以下各项的目的、结果和/或性能(所有类型)是否有任何差异:

Marshal.SizeOf(typeof(T))

Marshal.SizeOf(default(T))

?

最佳答案

第一个method接受一个类型,第二个 method举个例子。它们都返回关联结构的大小。

后一种方法调用前一种方法。这由 source 支持在 coreclr 中:

public static int SizeOf(Object structure)
{
if (structure == null)
throw new ArgumentNullException(nameof(structure));
// we never had a check for generics here
Contract.EndContractBlock();

return SizeOfHelper(structure.GetType(), true);
}

public static int SizeOf(Type t)
{
if (t == null)
throw new ArgumentNullException(nameof(t));
if (!(t is RuntimeType))
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(t));
if (t.IsGenericType)
throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(t));
Contract.EndContractBlock();

return SizeOfHelper(t, true);
}

一个重要的区别是,当使用引用类型时,您的一个调用将引发另一个不会引发的异常:

这会成功:

Marshal.SizeOf(typeof(AReferenceType))

这会出错(null 传递给方法)

Marshal.SizeOf(default(AReferenceType))

关于c# - Marshal.SizeOf(typeof(T)) 和 Marshal.SizeOf(default(T)) 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45412100/

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