【问题标题】:c# Interfaces - Implicit Conversion Error?c#接口 - 隐式转换错误?
【发布时间】:2012-12-01 16:54:10
【问题描述】:

如果我有这个界面:

public interface IFoo : IDisposable
{ 
    int PropA {get; set;}
    int PropB {get; set;}
}

还有一个班级:

public class Foo : IFoo
{
    public int PropA {get; set;}
    public int PropB {get; set;}

    public void Dispose()
    {
        Dispose();
        GC.SuppressFinalize(this);
    }
}

如果没有“无法隐式转换”错误,这是否应该工作?

    private Context context = new Context();
    private GenericRepository<IFoo> FooRepo;

    public GenericRepository<IFoo> Article
    {
        get
        {
            if (this.FooRepo == null)
            {
                this.FooRepo = new GenericRepository<Foo>(context);
            }
            return FooRepo;
        }
    }

我认为我做对了,正确的做法是什么?

【问题讨论】:

  • this.FooRepo = new GenericRepository&lt;IFoo&gt;(context);
  • 你可以使用这个方法:stackoverflow.com/questions/222403/…
  • 接口通则:类类型只用于构造;在其他任何地方使用接口类型。

标签: c# interface


【解决方案1】:

只有当GenericRepository&lt;T&gt; 在其泛型类型参数中为covariant 时,您正在尝试执行的操作(将GenericRepository&lt;Foo&gt; 引用分配给GenericRepository&lt;IFoo&gt; 类型的字段)才有效。为此,GenericRepository&lt;&gt; 将被定义为:

public class GenericRepository<out T> {...} //note the "out" modifier. 

那么这个任务就OK了:

this.FooRepo = new GenericRepository<IFoo>(context);

但是,这行不通,因为协方差仅限于接口委托。因此,为了在该限制内发挥作用,您可以定义一个协变的IGenericRepository&lt;T&gt; 接口并使用该接口而不是类:

public interface IGenericRepository<out T> {}
public class GenericRepository<T> : IGenericRepository<T> { }

private Context context = new Context();
private IGenericRepository<IFoo> FooRepo;

public IGenericRepository<IFoo> Article
{
    get
    {
        if (this.FooRepo == null)
        {
            this.FooRepo = new GenericRepository<Foo>(context);
        }
        return FooRepo;
    }
}

或者,如果GenericRepository&lt;T&gt; 实现IEnumerable,您可以使用Enumerable.Cast&lt;T&gt; 方法:

public IGenericRepository<IFoo> Article
{
    get
    {
        if (this.FooRepo == null)
        {
            this.FooRepo = new GenericRepository<Foo>(context).Cast<IFoo>();
        }
        return FooRepo;
    }
}

【讨论】:

    【解决方案2】:

    您正在尝试将上下文隐式转换为 Foo 而不是它的接口。另外,上下文是否实现了 IFoo?如果是,这应该可以工作。

    试试这个:

    private Context context = new Context();
    private GenericRepository<IFoo> FooRepo;
    
    public GenericRepository<IFoo> Article
    {
        get
        {
            if (this.FooRepo == null)
            {
                this.FooRepo = new GenericRepository<IFoo>(context);
            }
            return FooRepo;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-12
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 2016-06-21
      相关资源
      最近更新 更多