我正在研究只适用于引用类型的扩展方法。不过,我认为目前它正在装箱和拆箱。我怎样才能避免这种情况?如何在扩展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