В C# 7.0 появились деконструкторы, и мы можем создавать их для существующих классов/интерфейсов, используя методы расширения.
Я создал несколько методов деконструктора IList
public static void Deconstruct<TValue, TCollection>(this TCollection array, out TValue first, out TCollection rest)
where TCollection : IList<TValue>, new()
{
first = array[0];
rest = GetRestOfCollection<TValue, TCollection>(array, 1);
}
public static void Deconstruct<TValue, TCollection>(this TCollection array, out TValue first, out TValue second)
where TCollection : IList<TValue>, new()
{
if (array.Count != 2)
throw new InvalidOperationException(@"Collection.Count != 2");
first = array[0];
second = array[1];
}
private static TCollection GetRestOfCollection<TValue, TCollection>(TCollection array, int skip)
where TCollection : IList<TValue>, new() => new TCollection().AddRange(array.Skip(skip));
Я пытался использовать его с синтаксисом деконструкции
var ints = new List<int> { 1, 2 };
(int team1Score, int team2Score) = ints ;
Но это производит
Error CS8129: No suitable Deconstruct instance or extension method was found for type 'List<int>', with 2 out parameters and a void return type.
а также
Error CS0411: The type arguments for method 'ListExtensions.Deconstruct<TValue, TCollection>(TCollection, out TValue, out TCollection)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
Единственным рабочим вариантом является прямой вызов score.Deconstruct(out var team1,out int team2)
, но это устраняет преимущества деконструктора syxtex, так как я мог бы использовать любой метод для этой цели.
Так почему же компилятор не может найти подходящий Deconstruct method
? Выбор public static void Deconstruct<TValue, TCollection>(this TCollection array, out TValue first, out TValue second)
кажется очевидным.
Deconstruct(this IList<TValue> array, ...)
- person Evk   schedule 29.12.2017