【问题标题】:How to make a derived concrete class implicitly cast a generic base class?如何使派生的具体类隐式转换为泛型基类?
【发布时间】:2013-11-22 04:27:11
【问题描述】:

我有一个基本的抽象泛型类,它应该能够通过表达式获取对象的标识符:

public abstract class Entity<TId> where TId : IEquatable<TId>
{
    protected abstract Expression<Func<Entity<TId>, TId>> GetEntityId();
}

但是当我尝试从中派生(并实现抽象方法)时:

public class IntEntity : Entity<int>
{
    public int Id { get; set; }

    protected override Expression<Func<Entity<int>, int>> GetEntityId()
    {
        Expression<Func<IntEntity, int>> exp = e => e.Id;
        return exp; // CS0029 error
    }
}

我得到 CS0029 编译错误,说

不能隐式转换类型 'System.Linq.Expressions.Expression&lt;System.Func&lt;ConsoleApplication1.IntEntity,int&gt;&gt;' 到 'System.Linq.Expressions.Expression&lt;System.Func&lt;ConsoleApplication1.Entity&lt;int&gt;,int&gt;&gt;'

对此我有什么办法吗?

【问题讨论】:

    标签: c# generics


    【解决方案1】:

    这本质上是不安全的。

    如果这是合法的,您将能够将继承 Entity&lt;int&gt; 的不同类传递给只能接受 IntEntitys 的函数。

    相反,您可以使用CRTP:

    public abstract class Entity<TEntity, TId> 
        where TId : IEquatable<TId> 
        where TEntity : Entity<TEntity, TId>
    {
        protected abstract Expression<Func<TEntity, TId>> GetEntityId();
    }
    

    【讨论】:

    • +1:这正是我所需要的......我猜只有最后一个where 应该是where TEntity : Entity&lt;TEntity, TId&gt;
    猜你喜欢
    • 2016-11-15
    • 1970-01-01
    • 2015-02-13
    • 2011-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-22
    • 2014-03-22
    相关资源
    最近更新 更多