C# ValidationAttribute Redux
参考:C# ValidationAttribute Redux,c#,linq-to-sql,validation,lambda,C#,Linq To Sql,Validation,Lambda,参考: 好的。。。让我们重新思考这个问题: 从我撕下的代码: static TEntity Get<TEntity, TKey>(this DataContext ctx, TKey key) where TEntity : class { var table = ctx.GetTable<TEntity>(); var pkProp = (from member in ctx.Mapping.GetMetaType(typ
好的。。。让我们重新思考这个问题: 从我撕下的代码:
static TEntity Get<TEntity, TKey>(this DataContext ctx, TKey key) where TEntity : class
{
var table = ctx.GetTable<TEntity>();
var pkProp = (from member in ctx.Mapping.GetMetaType(typeof(TEntity)).DataMembers
where member.IsPrimaryKey
select member.Member).Single();
ParameterExpression param = Expression.Parameter(typeof(TEntity), "x");
MemberExpression memberExp;
switch (pkProp.MemberType)
{
case MemberTypes.Field: memberExp = Expression.Field(param, (FieldInfo)pkProp); break;
case MemberTypes.Property: memberExp = Expression.Property(param, (PropertyInfo)pkProp); break;
default: throw new NotSupportedException("Invalid primary key member: " + pkProp.Name);
}
Expression body = Expression.Equal(
memberExp, Expression.Constant(key, typeof(TKey)));
var predicate = Expression.Lambda<Func<TEntity, bool>>(body, param);
return table.Single(predicate);
}
正如我所说的,这些答案没有帮助。var枚举器= ((IEnumerable)表).GetEnumerator();对象 code=枚举数。MoveNext()? 枚举数。值:null代码>
在我尝试构建表达式树时没有用处IEnumerable tableGeneric= ((IEnumerable)表)代码>
尝试时出现问题:
objectcode=tableGeneric.FirstOrDefault(谓词)代码>
谢谢。据我所知,您可能想要的最终结果是,您确实需要一种类似以下的方法:
public bool IsValid<TEntity>()
{
// validation logic goes here
}
如果是这种情况,则使用所需的逻辑实现第一个代码块,然后实现第二个方法,如下所示:
public bool IsValidWrapper(Type entityType)
{
// You may want to be stricter than this, but the essence is to
// get a handle to the generic method first...
MethodInfo genMethod = GetType().GetMethod("IsValid");
// Bind it to the type you want to operate on...
MethodInfo method = genMethod.MakeGenericMethod(entityType);
// And invoke it...
return (bool) method.Invoke(this, null);
}
它不会赢得任何选美比赛或表演冠军,但它会满足你的需要。请注意,如果性能是一个问题,您可以使用签名bool delegate()
保持从Type
到委托的查找,这样您就不必对给定类型多次使用慢反射来执行类型绑定
public bool IsValid<TEntity>()
{
// validation logic goes here
}
public bool IsValid(Type entityType)
{
// ???
}
public bool IsValidWrapper(Type entityType)
{
// You may want to be stricter than this, but the essence is to
// get a handle to the generic method first...
MethodInfo genMethod = GetType().GetMethod("IsValid");
// Bind it to the type you want to operate on...
MethodInfo method = genMethod.MakeGenericMethod(entityType);
// And invoke it...
return (bool) method.Invoke(this, null);
}