ฉันมีปัญหาค่อนข้างง่าย แต่ดูเหมือนว่าจะไม่มีวิธีแก้ปัญหาภายใน C#
ฉันมีคลาส Foo
ประมาณ 100 คลาสโดยแต่ละคลาสใช้เมธอด static FromBytes()
นอกจากนี้ยังมีคลาสทั่วไปบางคลาสที่จะใช้วิธีการเหล่านี้เพื่อ FromBytes()
ของตัวเอง แต่คลาสทั่วไปไม่สามารถใช้เมธอด static FromBytes()
ได้ เนื่องจาก T.FromBytes(...)
ผิดกฎหมาย
ฉันพลาดบางสิ่งบางอย่างหรือไม่มีทางใช้ฟังก์ชันนี้ได้หรือไม่?
public class Foo1
{
public static Foo1 FromBytes(byte[] bytes, ref int index)
{
// build Foo1 instance
return new Foo1()
{
Property1 = bytes[index++],
Property2 = bytes[index++],
// [...]
Property10 = bytes[index++]
};
}
public int Property1 { get; set; }
public int Property2 { get; set; }
// [...]
public int Property10 { get; set; }
}
//public class Foo2 { ... }
// [...]
//public class Foo100 { ... }
// Generic class which needs the static method of T to work
public class ListOfFoo<T> : System.Collections.Generic.List<T>
{
public static ListOfFoo<T> FromBytes(byte[] bytes, ref int index)
{
var count = bytes[index++];
var listOfFoo = new ListOfFoo<T>();
for (var i = 0; i < count; i++)
{
listOfFoo.Add(T.FromBytes(bytes, ref index)); // T.FromBytes(...) is illegal
}
return listOfFoo;
}
}
ฉันคิดว่ามันไม่ยุติธรรมเลยที่จะเลือกคำตอบเป็นคำตอบที่ยอมรับ หลังจากที่คำตอบและความคิดเห็นทั้งหมดมีส่วนสนับสนุนในรูปแบบที่แตกต่างกันโดยมีมุมมองที่แตกต่างกัน คงจะดีถ้ามีคนเขียนภาพรวมที่ดีเกี่ยวกับวิธีการต่างๆ พร้อมข้อดีและข้อเสียของพวกเขา นั่นควรได้รับการยอมรับหลังจากที่มันช่วยนักพัฒนาในอนาคตได้ดีที่สุด
ListOfFoo<T>.FromBytes(...)
แบบคงที่ได้อย่างไร คุณจะต้องระบุอาร์กิวเมนต์ประเภทอยู่แล้วใช่ไหม ตัวอย่างเช่น:ListOfFoo<Foo1>.FromBytes(...)
จากนั้น คุณสามารถส่งผู้รับมอบสิทธิ์เป็นพารามิเตอร์เพิ่มเติมได้ (เช่น บริการที่เสนอ) หรือคุณเรียกมันผ่านการไตร่ตรอง? - person gehho   schedule 11.11.2013