クライアントまで、フルのC#4.0ができないのはなぜで、outパラメータ法でつくられる共変?

StackOverflow https://stackoverflow.com/questions/527758

  •  22-08-2019
  •  | 
  •  

質問

このような魔法のインターフェース:

public interface IHat<out TRabbit>
{
    TRabbit Take();
}

このクラス階層:

public class Rabbit { }

public class WhiteRabbit : Rabbit { }

できるようになっていをコンパイルす:

IHat<WhiteRabbit> hat1 = null;
IHat<Rabbit> hat2 = hat1;

あります。ものになっているのでしょうか?定義の異なる:

public interface IHat<out TRabbit>
{
    bool Take(out TRabbit r);
}

私がこの帽子が空の場合、別boolean戻り値(以前のバージョンが持っているのかもしれ返されるnull写から空の帽子).がってるやつばっかしだけ出力するうさぎのような論理的に異なる前のバージョン。

C#4.0コンパイラのCTPを与える誤差のインタフェース定義で必要とな'メソッドのパラメータの変タイプです。いない理由をこなし、それとも何かという点については将来のバージョンになっていますか?

役に立ちましたか?

解決

興味深い。しかし、CLIレベルがなければならないと思うか"なし"のみ"ref";ある属性をコンパイラでコンパイル(ための明確な課題)には"必要ないと考えています。

この制限は、CLIない"out"、"関係していることから、こうした.

他のヒント

だが、少し手間をお使いいただけますので共分散ラッパー:

public class CovariantListWrapper<TOut, TIn> : IList<TOut> where TIn : TOut
{
    IList<TIn> list;

    public CovariantListWrapper(IList<TIn> list)
    {
        this.list = list;
    }

    public int IndexOf(TOut item)
    {
        // (not covariant but permitted)
        return item is TIn ? list.IndexOf((TIn)item) : -1;
    }

    public TOut this[int index]
    {
        get { return list[index]; }
        set { throw new InvalidOperationException(); }
    }

    public bool Contains(TOut item)
    {
        // (not covariant but permitted)
        return item is TIn && list.Contains((TIn)item);
    }

    public void CopyTo(TOut[] array, int arrayIndex)
    {
        foreach (TOut t in this)
            array[arrayIndex++] = t;
    }

    public int Count { get { return list.Count; } }

    public bool IsReadOnly { get { return true; } }

    public IEnumerator<TOut> GetEnumerator()
    {
        foreach (TIn t in list)
            yield return t;
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public void Insert(int index, TOut item) { throw new InvalidOperationException(); }
    public void RemoveAt(int index) { throw new InvalidOperationException(); }
    public void Add(TOut item) { throw new InvalidOperationException(); }
    public void Clear() { throw new InvalidOperationException(); }
    public bool Remove(TOut item) { throw new InvalidOperationException(); }
}

ことができますのとしてコレクションで入力を参照しcovariantlyを作成することなく一戸建てコピーし、変更のが発見されたので、それらの共変微分。例:

class CovarianceWrapperExample
{
    class Person { }
    class Employee : Person { }

    void ProcessPeople(IList<Person> people) { /* ... */ }

    void Foo()
    {
        List<Employee> employees = new List<Employee>();

        // cannot do:
        ProcessPeople(employees);

        // can do:
        ProcessPeople(new CovariantListWrapper<Person, Employee>(employees));
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top