abstract class A
{
public static A Parse(byte[] buffer, int offset, int count)
{ ....} ....
}class B : A
{
public static B Parse(byte[] buffer, int offset, int count)
{ ....}
}class C : A
{
public static C Parse(byte[] buffer, int offset, int count)
{ ....}
}现在有个转换器会尝试对数据进行转换即
ParserController pc = new ParserController();
pc.TypeList.Add(typeof(B));
pc.TypeList.Add(typeof(C));然后分别通过反射来尝试转换:
foreach(Type type in pc.TypeList)
{
object obj = type.InvokeMember("Parse", BindingFlags.InvokeMethod | BindingFlags.Static, null, null, args);
if (obj != null)
{
break;
}
}
//注意ParserController无法预知B和C类,以后可能还是D、E(这现都是从A派生),只能依赖A。本来想通过多态来实现,无耐是静态方法。
不知各位有没有更好的方案?
{
public static A Parse(byte[] buffer, int offset, int count)
{ ....} ....
}class B : A
{
public static B Parse(byte[] buffer, int offset, int count)
{ ....}
}class C : A
{
public static C Parse(byte[] buffer, int offset, int count)
{ ....}
}现在有个转换器会尝试对数据进行转换即
ParserController pc = new ParserController();
pc.TypeList.Add(typeof(B));
pc.TypeList.Add(typeof(C));然后分别通过反射来尝试转换:
foreach(Type type in pc.TypeList)
{
object obj = type.InvokeMember("Parse", BindingFlags.InvokeMethod | BindingFlags.Static, null, null, args);
if (obj != null)
{
break;
}
}
//注意ParserController无法预知B和C类,以后可能还是D、E(这现都是从A派生),只能依赖A。本来想通过多态来实现,无耐是静态方法。
不知各位有没有更好的方案?
B、C生成或解析的实体二进制Buffer没有任何共性。
if (_Method != null) _Method.Invoke(null, new object[] { new byte[0], 1, 1 });
就不能写个Helper方法吗
你这种情况应该是使用实例方法using System;
using System.Collections.Generic;
using System.Reflection;abstract class A {
public virtual void Initialize(byte[] buffer, int offset, int count) {
// ....
} // ....
}class B : A {
public override void Initialize(byte[] buffer, int offset, int count) {
// ....
}
}class C : A {
public override void Initialize(byte[] buffer, int offset, int count) {
// ....
}
}public class Test {
public object[] Foo() {
ParserController pc = new ParserController();
pc.TypeList.Add(typeof(B));
pc.TypeList.Add(typeof(C)); List<object> result = new List<object>();
foreach (Type type in pc.TypeList)
{
object obj = Activator.CreateInstance(type);
MethodInfo mi = obj.GetType().GetMethod("Initialize");
if(mi != null) {
mi.Invoke(obj, args);
result.Add(obj);
}
}
return result.ToArray();
}
}