泛型接口编译,但在运行时不起作用

本文关键字:运行时 不起作用 编译 泛型接口 | 更新日期: 2023-09-27 18:17:29

我有一个通用接口的问题。编译器不给出任何编译错误,但在运行时抛出看不见的异常。

public interface IStructure
{
    string Name {get;}
}
public interface IStructureNavigation<T> : IStructure where T : IStructure
{
    T Parrent {get;}
}

public class ResourceStructure : IStructureNavigation<ResourceStructure>
{
    private ResourceStructure _parrent;
    public virtual string Name
    {
        get;
        set;
    }
    public virtual ResourceStructure Parrent
    {
        get { return _parrent; }
    }
}

有人能解释一下为什么下面的代码在运行时失败吗?

public class Action
{
    private ObjectContext _context;
    private ObjectSet<ResourceStructure> _structue;
    private IQueryable<ResourceStructure > _parrents;
    public Action()
    {
        string connectionString =
             ConfigurationManager
            .ConnectionStrings["Structure"].ConnectionString;
        _context = new ObjectContext(connectionString);
        _context.ContextOptions.LazyLoadingEnabled = true;
        _structue = _context.CreateObjectSet<ResourceStructure>();
        _parrents = _structue.Where(x => x.ParentID == null);

       // FAILS IN FOREACH LOOP : UNSEEN EXCPTION
       foreach (IStructureNavigation<IStructure> strt in _parrents)
        {
            //do something
        }

       //WORKS IF USING CONCRETE TYPE NOT INTERFACE
       foreach(IStructureNavigation<ResourceStructure > strt in _parrents)
        {
            //do something
        }
    }
}

泛型接口编译,但在运行时不起作用

声明T为协变

  public interface IStructureNavigation<out T> : IStructure where T : IStructure

这是因为您的实例类型是IStructureNavigator<ResourceStructure>而不是IStructureNavigator<IStructure>

如果需要使用接口,可以使用Cast扩展方法:

_parrents =  _context.CreateObjectSet<ResourceStructure>().Cast<IStructure>();

您使用的是哪个版本的框架?