に不変有効でなければなりません。 IRepository.GetAll() '。' T 'は共変です。このエラーを解決するには?無効な差異:</p> <p>「無効な差異:型パラメータ 『T』のConsoleApplication1」に不変有効でなければならない型パラメータ「T」を私はコンパイル時に以下のエラーメッセージを抱えている
以下は私のコードです:私は必要があるだろう何
class Program
{
static void Main(string[] args)
{
IRepository<BaseClass> repository;
repository = new RepositoryDerived1<Derived1>();
Console.ReadLine();
}
}
public abstract class BaseClass
{
}
public class Derived1 : BaseClass
{
}
public interface IRepository<out T> where T: BaseClass, new()
{
IList<T> GetAll();
}
public class Derived2 : BaseClass
{
}
public abstract class RepositoryBase<T> : IRepository<T> where T: BaseClass, new()
{
public abstract IList<T> GetAll();
}
public class RepositoryDerived1<T> : RepositoryBase<T> where T: BaseClass, new()
{
public override IList<T> GetAll()
{
throw new NotImplementedException();
}
}
はこのように上記のクラスを使用できるようにすることです:
IRepositoryリポジトリ。
または
RepositoryBase repository; )(
リポジトリ=新しいRepositoryDerived1;:
は、それから私はこのような何かを割り当てることができるようにしたいのですが
しかし、IRepositoryクラスでコンパイル時エラーが発生します。
私はIRepositoryクラスから「アウト」のキーワードを削除した場合、それは
「RepositoryDerived1は」「IRepository」に変換することができないことを私は別のエラーが発生します。
なぜ、どのように修正するのですか?
おかげ
を定義しRepositoryDerived1'されています。あなたは
IEnumerable<T>
からIList<T>
を変更し、IRepository<out T>
から: new()
制約を削除した場合、それは動作します(抽象基底クラスはそれを満たしていないとして)? –@Jeremyコードサンプルに表示されています –
@Marc - ああ、スクロールバーを見逃しました。イェーに感謝します。 –