การอนุมานประเภท c# deconstructors [ซ้ำกัน]

C# 7.0 เปิดตัว deconstructors และเราสามารถสร้างมันสำหรับคลาส/อินเทอร์เฟซที่มีอยู่โดยใช้วิธีการขยาย

ฉันได้สร้างวิธี deconsructor ของ 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) แต่สิ่งนี้จะช่วยลดประโยชน์ของ deconstructor syxtex เนื่องจากฉันสามารถใช้วิธีการใดก็ได้เพื่อการนี้

เหตุใดคอมไพเลอร์จึงไม่พบ Deconstruct method ที่เหมาะสม เห็นได้ชัดว่าต้องเลือก public static void Deconstruct<TValue, TCollection>(this TCollection array, out TValue first, out TValue second)


person Sic    schedule 29.12.2017    source แหล่งที่มา
comment
สำเนาจริงอยู่ที่นี่: stackoverflow.com/q/46840305/5311735 อย่างไรก็ตาม หากคุณต้องการให้สิ่งนี้ใช้งานได้ - ใช้ Deconstruct(this IList<TValue> array, ...)   -  person Evk    schedule 29.12.2017