我正在研究只適用於引用類型的擴展方法。不過,我認爲目前它正在裝箱和拆箱。我怎樣才能避免這種情況?如何在擴展System.Object時避免裝箱/取消裝箱?
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
有趣的是,它不是拳擊。此代碼編譯爲: int i = 1; i.GetOrDefaultIfNull((o)=> o.ToString(),「」); 感謝「Where T:class」這是我真正想要的。 – 2010-04-09 17:34:02