خلاص شدن از شر deep null check
نویسنده: رفیعی
تاریخ: ۱۳۹۳/۰۱/۳۰ ۱۲:۴۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
var store = GetStore(); string postCode = null; if (store != null && store.Address != null && store.Address.PostCode != null) postCode = store.Address.PostCode.ToString();
public static TResult IfNotNull<TResult, TSource>(
this TSource source,
Func<TSource, TResult> onNotDefault)
where TSource : class
{
if (onNotDefault == null) throw new ArgumentNullException("onNotDefault");
return source == null ? default(TResult) : onNotDefault(source);
} var postCode = GetStore() .IfNotNull(x => x.Address) .IfNotNull(x => x.PostCode) .IfNotNull(x => x.ToString());
public static TResult IfNotDefault<TResult, TSource>(
this TSource source,
Func<TSource, TResult> onNotDefault,
Predicate<TSource> isNotDefault = null)
{
if (onNotDefault == null) throw new ArgumentNullException("onNotDefault");
var isDefault = isNotDefault == null
? EqualityComparer<TSource>.Default.Equals(source, default(TSource))
: !isNotDefault(source);
return isDefault ? default(TResult) : onNotDefault(source);
} return person . IfNotDefault(x => x.Name) . IfNotDefault(SomeOperation, x => !string.IsNullOrEmpty(x));
var avg = students .Where(IsNotAGraduate) .FirstOrDefault() .IfNotDefault(s => s.Grades) .IfNotDefault(g => g.Average(), g => g != null && g.Length > 0);
public class Customer
{
public CustomerInfo Info { get; set; }
public Int32 GetNameLength()
{
return this.IfNotDefault(city => city.Info)
.IfNotDefault(info => info.CityInfo)
.IfNotDefault(cityInfo => cityInfo.Name)
.IfNotDefault(name => name.Length);
}
}
public class CustomerInfo
{
public CustomerCityInfo CityInfo { get; set; }
}
public class CustomerCityInfo
{
public String Name { get; set; }
} Customer customer = new Customer(); String cityName = customer .IfNotDefault(cust => cust.Info) .IfNotDefault(info => info.CityInfo) .IfNotDefault(city => city.Name); Int32 length = customer.GetNameLength();
public static TValue GetValue<TObj, TValue>(this TObj obj, Func<TObj, TValue> member, TValue defaultValueOnNull = default(TValue))
{
if (member == null)
throw new ArgumentNullException("member");
if (obj == null)
throw new ArgumentNullException("obj");
try
{
return member(obj);
}
catch (NullReferenceException)
{
return defaultValueOnNull;
}
} public class Customer
{
public CustomerInfo Info { get; set; }
public Int32 GetNameLength()
{
return this.Info.CityInfo.Name.Length;
}
}
public class CustomerInfo
{
public CustomerCityInfo CityInfo { get; set; }
}
public class CustomerCityInfo
{
public String Name { get; set; }
} Customer customer = new Customer();
String cityName = customer.GetValue(cust => cust.Info.CityInfo.Name, "Not Selected");
Int32 i = customer.GetValue(cust => cust.GetNameLength());