C# 用泛型接口属性重写非泛型接口属性

C# 用泛型接口属性重写非泛型接口属性,c#,inheritance,interface,generics,C#,Inheritance,Interface,Generics,我有两个界面,如下所示: public interface IEntityViewModel<T> : IEntityViewModel where T : class, ICLEntity { new T Entity { get; set; } } public interface IEntityViewModel { void LoadEntity(int primaryKey); bool? DialogResult { get; s

我有两个界面,如下所示:

public interface IEntityViewModel<T> : IEntityViewModel where T : class, ICLEntity
{
    new T Entity { get; set; }
}

public interface IEntityViewModel
{        
    void LoadEntity(int primaryKey);
    bool? DialogResult { get; set; }
    ICLEntity Entity { get; set; }        
}
但是我在类中得到了两个实体属性,这不是我需要的。如果实现泛型接口,我需要Entity属性的类型为T,如果是非泛型属性,则需要类型为Ictintity

如何做到这一点?我错过了一些简单的东西吗?我正在使用.NET4.0,协方差可以帮我吗


谢谢

我认为这是办不到的。你已经尽了最大的努力了

public abstract class EntityConductor<T> : IEntityViewModel<T>
    where T : class, ICLEntity
{
    public T Entity { get; set; }

    ICLEntity IEntityViewModel.Entity
    {
        get { return Entity; }
        set { Entity = (T)value; }
    }
}
公共抽象类EntityConductor:IEntityViewModel
其中T:类,i实体
{
公共T实体{get;set;}
ICEntity EntityViewModel.Entity
{
获取{return Entity;}
设置{Entity=(T)值;}
}
}
这将确保在使用IEntityViewModel对象时可以使用强类型属性,但如果您只知道它是IEntityViewModel对象,则将使用弱类型属性。没有额外的存储需求,所以我看不出这有什么问题。此构造反映了您的使用场景—您有一个对象,但在某些情况下,您可能没有允许使用强类型属性的类型信息

作为旁注,如果参数类型错误,Entity中的setter应该抛出异常

ICLEntity IEntityViewModel.Entity
    {
        get
        {
            return ActiveItem.Entity;
        }
        set
        {
            ActiveItem.Entity = value as T;
        }
    }
public abstract class EntityConductor<T> : IEntityViewModel<T>
    where T : class, ICLEntity
{
    public T Entity { get; set; }

    ICLEntity IEntityViewModel.Entity
    {
        get { return Entity; }
        set { Entity = (T)value; }
    }
}