当我读到Deep Null检查时,会出现这种担忧 ,有没有更好的方法?
还有这个
假设我想检查所有属性是否为null或者是否有任何属性为null.(浅物业)
SearchCriteria对象:
Keyword (Searches Name and Description) != null ||
SectorId != null ||
IndustryId != null ||
HasOption != null ||
HasFutures != null ||
30 properties to go...
Run Code Online (Sandbox Code Playgroud)
我们可以看到,语法在某种程度上难以阅读.我想要类似的东西
SearchCriteria
.Has(criteria => criteria.Keywork)
.Has(criteria => criteria.SectorId)
.Has(criteria => criteria.HasOption)
.etc
Run Code Online (Sandbox Code Playgroud)
(如果我们想要以上所有属性都不为null)
要么
SearchCriteria
.Has(criteria => criteria.Keywork).Or()
.Has(criteria => criteria.SectorId).Or()
.Has(criteria => criteria.HasOption).Or()
.etc
Run Code Online (Sandbox Code Playgroud)
(如果我们想要任何属性为非null)
要么
SearchCriteria
.Has(criteria => criteria.Keywork).Or()
.Has(criteria => criteria.SectorId)
.Has(criteria => criteria.HasOption)
.etc
Run Code Online (Sandbox Code Playgroud)
(如果我们想要Keyword 或 SectorId具有值并且 HasOption具有值.
那么我们在codeplex上有任何现有的项目吗?或者任何可以结合深度空检查和浅空检查的优雅方法?
坦率地说,我会用简单的版本涉及粘||
或&&
,== null
或!= null
.它直接有效,并允许立即短路.如果你打算做这个地段,你也许可以编写一个使用元编程(公用类Expression
或ILGenerator
可能)每一次型,检查所有属性来创建一个优化的方法,那么:
if(MyHelper.AllNull(obj)) ... // note this is probably actually generic
Run Code Online (Sandbox Code Playgroud)
完整示例:
using System;
using System.Linq.Expressions;
using System.Reflection;
static class Program
{
static void Main()
{
bool x = MyHelper.AnyNull(new Foo { }); // true
bool y = MyHelper.AnyNull(new Foo { X = "" }); // false
}
}
class Foo
{
public string X { get; set; }
public int Y { get; set; }
}
static class MyHelper
{
public static bool AnyNull<T>(T obj)
{
return Cache<T>.AnyNull(obj);
}
static class Cache<T>
{
public static readonly Func<T, bool> AnyNull;
static Cache()
{
var props = typeof(T).GetProperties(
BindingFlags.Instance | BindingFlags.Public);
var param = Expression.Parameter(typeof(T), "obj");
Expression body = null;
foreach(var prop in props)
{
if (!prop.CanRead) continue;
if(prop.PropertyType.IsValueType)
{
Type underlyingType = Nullable.GetUnderlyingType(
prop.PropertyType);
if (underlyingType == null) continue; // cannot be null
// TODO: handle Nullable<T>
}
else
{
Expression check = Expression.Equal(
Expression.Property(param, prop),
Expression.Constant(null, prop.PropertyType));
body = body == null ? check : Expression.OrElse(body, check);
}
}
if (body == null) AnyNull = x => false; // or true?
else
{
AnyNull = Expression.Lambda<Func<T, bool>>(body, param).Compile();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
683 次 |
最近记录: |