введите сюда код using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Generics { abstract class Animals { } class Tigers : Animals { } interface Igetting<out T> { // void Add(T element); T this[int index1] { get; } } class MyList<T>:Igetting<T> { //поля private int elements=0; private T[] array; public int Elements { get { return elements; } } public MyList(params T[] array) { this.array = array; elements = array.Length; } //реализуемые методы public void Add(T element) { T[] new_array = new T[elements+1]; for (int i = 0; i < elements; i++) { new_array[i] = array[i]; } new_array[new_array.Length - 1] = element; array = new_array; elements++; } public T this[int index1] { get { return array[index1]; } } } class Program { static void Main(string[] args) { MyList<Tigers> mys = new MyList<Tigers>(new Tigers(), new Tigers(), new Tigers()); Igetting<Animals> obj = mys; for (int i = 0; i < mys.Elements; i++) { Console.WriteLine(obj[i].GetType().ToString()); } Console.ReadKey(); } } 

}

I want to add the Add (T element) method in the generic interface but do not allow Why? Thank you in advance

    1 answer 1

    Because you defined T as out T This means that the following code will work:

     Igetting<Animals> list = new MyList<Tigers>(...); Animals x = list[0]; 

    This works list[0] has a real Tigers type, which means that it can be assigned to a reference to the type Animals .

    Now imagine that the compiler would allow you to add a void Add(T element) to the interface . Then you could write this:

     Igetting<Animals> list = new MyList<Tigers>(...); list.Add(new Lions()); // это должно откомпилироваться, ведь Lions - подкласс Animals 

    Catastrophe! You got an element of type Lions , not Tigers in the Add method of the class MyList<Tigers> ! So that such catastrophes were impossible, the compiler prohibits you to add an “incoming” parameter with an out type.

    A simple rule: out types can only be used for outgoing parameters, that is, for return values.


    What to do?

    • You can add a method only to the class, but not to the interface.
    • Or you can get a separate interface IAdding<in T> , in which to add the desired method. And let the class implement both interfaces at the same time.
    • Well, or you can just remove out of the original interface.