通用接口编译但在运行时不起作用

时间:2011-12-12 15:10:57

标签: c# generics interface

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

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
        }
    }
}

2 个答案:

答案 0 :(得分:4)

将T声明为协变

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

答案 1 :(得分:0)

这是因为您的实例属于IStructureNavigator<ResourceStructure>而非IStructureNavigator<IStructure>

如果您需要使用界面,可以使用Cast扩展方法:

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

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