C# 7.0 memperkenalkan dekonstruktor dan kami dapat membuatnya untuk kelas/antarmuka yang ada menggunakan metode ekstensi.
Saya telah membuat beberapa metode dekonstruktor 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));
Saya sudah mencoba menggunakannya dengan sintaks dekonstruksi
var ints = new List<int> { 1, 2 };
(int team1Score, int team2Score) = ints ;
Tapi itu menghasilkan
Error CS8129: No suitable Deconstruct instance or extension method was found for type 'List<int>', with 2 out parameters and a void return type.
Dan
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.
Satu-satunya opsi yang berfungsi adalah panggilan langsung score.Deconstruct(out var team1,out int team2)
, tetapi ini menghilangkan manfaat syxtex dekonstruktor, karena saya dapat menggunakan metode apa pun untuk tujuan ini.
Jadi mengapa kompiler tidak dapat menemukan Deconstruct method
yang cocok? Tampaknya jelas untuk memilih 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