gpt4 book ai didi

c# - 扩展 System.Object 时如何避免装箱/拆箱?

转载 作者:行者123 更新时间:2023-11-30 14:42:56 26 4
gpt4 key购买 nike

我正在开发一种仅适用于引用类型的扩展方法。但是,我认为它目前正在对值进行装箱和拆箱。我怎样才能避免这种情况?

namespace System
{
public static class SystemExtensions
{
public static TResult GetOrDefaultIfNull<T, TResult>(this T obj, Func<T, TResult> getValue, TResult defaultValue)
{
if (obj == null)
return defaultValue;
return getValue(obj);
}
}
}

示例用法:

public class Foo
{
public int Bar { get; set; }
}

在一些方法中:

Foo aFooObject = new Foo { Bar = 1 };
Foo nullReference = null;

Console.WriteLine(aFooObject.GetOrDefaultIfNull((o) => o.Bar, 0)); // results: 1
Console.WriteLine(nullReference.GetOrDefaultIfNull((o) => o.Bar, 0)); // results: 0

最佳答案

那不是拳击。您认为它在哪里 拳击?如果是因为您查看了“==”周围的 IL,请不要让它愚弄您 - JIT 将决定在这里做什么。它有机会为每个 (T, TResult) 对生成不同的 native 代码。事实上,代码将对所有引用类型共享,而对值类型则不同。所以你最终会得到:

T = string, TResult = int (native code #1)
T = Stream, TResult = byte (native code #2)
T = string, TResult = byte (native code #2)
T = Stream, TResult = string (native code #3)

话虽如此,如果您想将扩展方法限制为引用类型,请这样做:

public static TResult GetOrDefaultIfNull<T, TResult>
(this T obj, Func<T, TResult> getValue, TResult defaultValue)
where T : class

IL 中仍然会有一个盒子,但别担心 - 实际上不会发生装箱。毕竟,什么可以装箱?您提供的是引用,而引用本身永远不会装箱 - 只有值类型的值才会装箱。

关于c# - 扩展 System.Object 时如何避免装箱/拆箱?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2609054/

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