如何将泛型类型T转换为接口?

时间:2017-04-18 07:57:41

标签: c# generics

我写了一个通用的更新方法,如下所示:

int UpdateBy(Expression<Func<T, bool>> filterExpression, Expression<Func<T, T>> updateExpression) where T : class, new()
{
    int result;
    //if T implements IModel interface, then I would like to modify pdateExpression here 
    {
        //UpdateTime is the member of interface IModel, without casting T to IModel interface, this line of code will not compile
        Expression<Func<T, T>> upexp = s => new T {UpdateTime = DateTime.Now}; 
        result = GetRepository<T>().UpdateBy(filterExpression, ExpressionCombiner.Combine(updateExpression, upexp));
    }
    else
    {
        //T doesn't implement IModel interface, so update it directly
        result= GetRepository<T>().UpdateBy(filterExpression, updateExpression);
    }

    return result;
}

如何使上面的代码编译并正确运行?提前谢谢!

0 个答案:

没有答案