简体   繁体   English

泛型函数和值类型

[英]Generic functions and value types

Do generic functions work well with nullable value types, or do they box behind the scenes? 泛型函数与可空值类型一起使用是否很好,还是它们在幕后?

For example I have a helper function like this: 例如,我有一个这样的辅助函数:

public static TResult Return<TInput, TResult>(this TInput o, Func<TInput, TResult> evaluator, TResult failureValue)
    where TInput : class
{
    if (o == null) return failureValue;
    return evaluator(o);
}

Which I use to offer a fallback value when something is null, eg 当某项为空时,我用来提供后备值,例如

var log = person.Return(p => p.log, emptylog)

So depending on whether log is a value or reference type, do I need a specialised version of Return() to handle value types without boxing, or is the above good for all cases? 因此,根据log是值类型还是引用类型,我是否需要特殊版本的Return()来处理值类型而无需装箱,或者上述方法对所有情况都适用吗?

EDIT: I'm curious as to why the author of this http://pastebin.com/vdS1uNu1 has specializations for class -> struct, class -> class, etc. 编辑:我很好奇为什么此http://pastebin.com/vdS1uNu1的作者具有类->结构,类->类等的专业化知识。

No, that won't box value types - but it will cause a new native implementation of the method to be created (at JIT time) each time you use a different value type for TResult , whereas all reference types will share the same native code. 不,不会将值类型装箱-每次您为TResult使用不同的值类型时, 它将导致在JIT时间创建该方法的新本机实现,而所有引用类型将共享相同的本机代码。 That's very rarely a problem though - it's not like it's a per-call overhead. 这是很少一个问题-它不喜欢它的每次呼叫的开销。 It's that "create the right native code based on the type argument" that allows it to avoid boxing. 正是这种“基于类型参数创建正确的本机代码”,使其避免装箱。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM