【问题标题】:Problems with generics泛型问题
【发布时间】:2012-11-30 23:35:20
【问题描述】:

我遇到了泛型问题:

public interface IEntity {}

public class User : IEntity {}

public class Experiments {
    private IList<IEntity> list;
    private IList<Action<IEntity>> actions;

    public Experiments(){
        list = new List<IEntity>();
        actions = new List<Action<IEntity>>();
    }

    public void Add<T>(T entity) where T : IEntity {
        list.Add(entity); // -> NO PROBLEM HERE
    }

    public void AddAction<T>(Action<T> handle) where T : IEntity {
        actions.Add(handle); // -> HERE I GET AN ERROR
    }

为什么我得到"cannot convert from 'System.Action' to 'System.Action..." 一旦我在方法的签名上指定了 T 是 IEntity?

【问题讨论】:

  • IEntity != IEntityCheck
  • 您是否复制了正确的错误信息?当我编译它时,我得到:'System.Collections.Generic.ICollection>.Add(System.Action)' 的最佳重载方法匹配有一些无效参数
  • 如果你知道T 是一个IEntity,为什么不使用IEntity 而不是泛型呢?
  • @JohnKalberer 查看我在 JG in SD 的回答下的评论。

标签: c# asp.net c#-4.0 generics interface


【解决方案1】:

我设法通过在类级别声明泛型类型来编译它。

public interface IEntity { }

public class User : IEntity { }

public class Experiments<T> where T : IEntity
{
    private IList<T> list;
    private IList<Action<T>> actions;

    public Experiments()
    {
        list = new List<T>();
        actions = new List<Action<T>>();
    }

    public void Add(T entity)
    {
        list.Add(entity);
    }

    public void AddAction(Action<T> handle)
    {
        actions.Add(handle);
    }
}

【讨论】:

    【解决方案2】:

    试试:

    public void AddAction(Action<IEntity> handle) 
    {
        actions.Add(handle);
    }
    

    而你的add函数不需要添加类型参数,直接使用接口即可。

    public void Add(IEntity entity)
    {
        list.Add(entity);
    }
    

    public void AddAction&lt;T&gt;(T entity) where T : IEntity 的问题是我可以(如果可行的话)传入像 Foo(ConcreteEntity entity) 这样的函数,该函数使用具体类上的成员,但未在接口上定义,那么我将无法循环通过Actions&lt;IEntity&gt; 的列表并使用IEntity 的其他一些实现来调用它们,并让它们都成功。

    【讨论】:

    • 当然可以,但我想问题是public void Add&lt;T&gt;(T entity) where T : IEntity有什么问题
    • JG,如果您认为这是解释,请不要回复我的评论并更新您的答案。
    • +1 我想你明白了,但它需要更好的解释。可能有一些例子。
    【解决方案3】:

    谢谢大家的回答,我找到了解决问题的方法。

    我刚刚将操作 List> 更改为 List,现在一切正常......

    ...
    private IList<IEntity> list;
    private IList<Delegate> actions;
    
    public void AddAction<T>(Action<T> handle) where T : IEntity {
        actions.Add(handle);
    }
    ...
    

    谢谢。

    【讨论】:

      猜你喜欢
      • 2011-11-04
      • 2011-01-07
      • 1970-01-01
      • 2014-01-01
      • 1970-01-01
      相关资源
      最近更新 更多