试图让通用在通用的不可用 [英] Trying to get generic when generic is not available

查看:130
本文介绍了试图让通用在通用的不可用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想开发一些通用的定制ValidationAttributes。事实上,一个人不能创建属性的一个通用的子类,是让我疯了。

I am trying to develop some general purpose custom ValidationAttributes. The fact that one cannot create a generic subclass of an attribute is making me nuts.

下面是我在ValidationAttribute和isValid重写代码验证的价值属性是独特的:

Here is my code for the IsValid override in a ValidationAttribute to verify that the value of a property is unique:

    public override bool IsValid(object value)
    {
        SomeDataContext context = SomeDataContext.GetNewDataContext();
        Type tableType = typeof(Table<>).MakeGenericType(new Type[] { _EntityType });
        var table = Activator.CreateInstance(tableType);
        //ITable table = context.GetTable(_EntityType);
        var codeProp = (from member in context.Mapping.GetMetaType(_EntityType).DataMembers
                        where member.Name == _PropertyName
                        select member.Member).Single();
        ParameterExpression param = Expression.Parameter(_EntityType, "x");
        MemberExpression memberExp = Expression.Property(param, (PropertyInfo)codeProp); 
        Expression body = Expression.Equal(memberExp, Expression.Constant(value, typeof(char)));
        //var predicate = Expression.Lambda<Func<TEntityType, bool>>(body, param);
        Type lambdaType = typeof(Func<,>).MakeGenericType(_EntityType, typeof(bool));
        var predicate = Expression.Lambda(lambdaType, body, param);
        object code = table.FirstOrDefault(predicate);
        if (code != null)
        {
            return false;
        }
        return true;
    }

这行:

目标代码= table.FirstOrDefault(谓语);

object code = table.FirstOrDefault(predicate);

错误的:

对象不包含FirstOrDefault没有扩展名......等的定义。

'object' does not contain a definition for 'FirstOrDefault' and no extension ......etc.

如何定义,铸造或以其他方式让编译器来识别表作为事情暴露了一个.FirstOrDefault方法?

How do I define, cast or otherwise get the compiler to recognize "table" as something that exposes a .FirstOrDefault method?

感谢

推荐答案

这将让你到一个类型System.Linq.Enumerable可以使用:

This will get you to a type that System.Linq.Enumerable can use:

IEnumerable<object> tableGeneric =
  ((IEnumerable)table).OfType<object>();



三个关注点:

Three concerns:


  1. 请不要使用VAR这么多 - 你会失去跟踪你的类型

  2. 我不能确定如何使用在FirstOrDefault打电话给你的断言 - 我不明白如何编译器可以输入检查。 http://msdn.microsoft.com/en-us/library/bb299425.aspx

  3. 如果你得到的谓词工作,。任何()可能比.FirstOrDefault()

这篇关于试图让通用在通用的不可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆