2

このインターフェースがある場合:

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

私はそれが正しいと思っていましたが、これを行う正しい方法は何ですか?

4

2 に答える 2

3

What you're trying to do (assigning GenericRepository<Foo> reference to a field of type GenericRepository<IFoo>) would only work if GenericRepository<T> were covariant in its generic type parameter. For that, GenericRepository<> would be defined as:

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

then this assignment would be OK:

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

However, that won't work because covariance is limited to interfaces and delegates. So, in order to play within that limitation, you can define a covariant IGenericRepository<T> interface and use the interface instead of the class:

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

Alternatively, if GenericRepository<T> implements IEnumerable you can use the Enumerable.Cast<T> method:

public IGenericRepository<IFoo> Article
{
    get
    {
        if (this.FooRepo == null)
        {
            this.FooRepo = new GenericRepository<Foo>(context).Cast<IFoo>();
        }
        return FooRepo;
    }
}
于 2012-12-13T19:17:39.727 に答える
1

インターフェイスではなく、暗黙的にコンテキストを Foo に変換しようとしています。また、Context は 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;
    }
}
于 2012-12-13T18:23:11.173 に答える