【发布时间】:2013-11-23 07:36:54
【问题描述】:
我有一个相当简单的问题,但在 C# 中似乎没有解决方案。
我有大约 100 个 Foo 类,每个类都实现了一个 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;
}
}
我认为选择一个答案作为公认答案是不公平的,毕竟所有答案和 cmets 都以不同的方式做出了贡献,他们的观点不同。如果有人对不同方法的优缺点进行了很好的概述,那就太好了。在它对未来的开发者有最大的帮助之后应该被接受。
【问题讨论】:
-
尝试扩展方法。
-
嗨@Muctadir,不幸的是,我在泛型扩展方法中遇到了与泛型类中相同的问题。
-
如何调用静态
ListOfFoo<T>.FromBytes(...)方法?无论如何,您都必须指定类型参数,不是吗?例如:ListOfFoo<Foo1>.FromBytes(...)。然后您可以将委托作为附加参数传递(如Servy proposed)。还是通过反射调用它?
标签: c# generics reflection