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。本来想通过多态来实现,无耐是静态方法。
不知各位有没有更好的方案?

解决方案 »

  1.   

    附加:
    B、C生成或解析的实体二进制Buffer没有任何共性。
      

  2.   

     MethodInfo _Method = T.GetMethod("Parse", BindingFlags.InvokeMethod | BindingFlags.Static|BindingFlags.Public);
                if (_Method != null) _Method.Invoke(null, new object[] { new byte[0], 1, 1 });
      

  3.   

    静态方法 还多态。
    就不能写个Helper方法吗
      

  4.   

    修正方案本身
    你这种情况应该是使用实例方法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();
        }
    }