繁体   English   中英

处理创建大量子类型对象的最佳方法

[英]Best way to handle creation of large number of subtype objects

我有一个基本的Message类,以及大约100个不同的Message子类型类,它们代表可以处理的每种消息类型。 我目前正在考虑使用巨型switch语句创建消息对象。 例如:

switch (MsgType)
{
   case MessageType.ChatMsg:
      Msg = new MsgChat(Buf);
      break;
   case MessageType.ResultMsg:
      Msg = new MsgResult(Buf);
      break;
   ... // 98 more case statements
}
Msg.ProcessMsg(); // Use a polymorphic call to process the message.

有一个更好的方法吗? 如果是这样,您可以显示一个简单的代码示例。

编辑

因此,我尝试这样做:

public class Test
{
   public Test()
   {
      IEnumerable<Type> myEnumerable = GetTypesWith<MyAttribute>(true);
   }

   IEnumerable<Type> GetTypesWith<TAttribute>(bool inherit)
      where TAttribute : System.Attribute
   {
      return from a in AppDomain.CurrentDomain.GetAssemblies()
             from t in a.GetTypes()
             where t.IsDefined(typeof(TAttribute), inherit)
             select t;
   }
}

这似乎起作用,因为myEnumerable现在包含所有100个消息子类型,以及基本消息类型。 但是,尽管我不介意在程序开始时使用反射来加载类型,但是使用它来实时访问适当的对象可能太慢了。 因此,我想尝试使用委托。

@Mark Hildreth在下面的注释中的示例:

“所以,您将有一个>的字典。那么,您的映射将是mappings [MessageType.ChatMsg] = x => new MsgChat(x);”

有两种方法可以解释此代码。 一种想法是删除所有100个子类,而只使用一个具有100个委托方法的大型类。 那是遥远的第二选择。 另一个想法也是我的第一选择,就是让上述代码以某种方式创建消息子类对象。 但是,我不太了解它将如何做到这一点。 同样,将上述技术保留在我的Test类中来获取所有类型或委托,而不必编写所有100个类型或委托,将是很好的。 您或其他任何人都可以解释如何做到这一点吗?

您可以定义一个Dictionary将每个MessageType值映射到其定义的Message派生类,并使用此映射数据创建一个实例,而不是使用巨型switch语句。

字典定义:

Dictionary<int, Type> mappings = new Dictionary<int, Type>();
mappings.Add(MessageType.ChatMsg, typeof(MsgChat));
mappings.Add(MessageType.ResultMsg, typeof(MsgResult));

...

词典消耗:

ConstructorInfo ctor = mappings[MessageType.ChatMsg].GetConstructor(new[] { typeof(Buf) });
Message message = (Message)ctor.Invoke(new object[] { Buf });

请注意,我没有编译此代码来验证是否正确。 我只想告诉你这个主意。

编辑

我有新的答案可以改善第一个答案。 我正在考虑使用@MikeSW@Mark Hildreth给出的想法来解决您编辑过的问题。

public class FactoryMethodDelegateAttribute : Attribute
{
    public FactoryMethodDelegateAttribute(Type type, string factoryMethodField, Message.MessageType typeId)
    {
        this.TypeId = typeId;
        var field = type.GetField(factoryMethodField);
        if (field != null)
        {
            this.FactoryMethod = (Func<byte[], Message>)field.GetValue(null);
        }
    }

    public Func<byte[], Message> FactoryMethod { get; private set; }
    public Message.MessageType TypeId { get; private set; }
}

public class Message
{
    public enum MessageType
    {
        ChatMsg,
    }
}

[FactoryMethodDelegate(typeof(ChatMsg), "FactoryMethodDelegate", Message.MessageType.ChatMsg)]
public class ChatMsg : Message
{
    public static readonly MessageType MessageTypeId = MessageType.ChatMsg;
    public static readonly Func<byte[], Message> FactoryMethodDelegate = buffer => new ChatMsg(buffer);
    public ChatMsg(byte[] buffer)
    {
        this.Buffer = buffer;
    }

    private byte[] Buffer { get; set; }
 }

public class TestClass
{
    private IEnumerable<Type> GetTypesWith<TAttribute>(bool inherit) where TAttribute : Attribute
    {
        return from a in AppDomain.CurrentDomain.GetAssemblies()
               from t in a.GetTypes()
               where t.IsDefined(typeof(TAttribute), inherit)
               select t;
    }

    [Test]
    public void Test()
    {
        var buffer = new byte[1];
        var mappings = new Dictionary<Message.MessageType, Func<byte[], Message>>();
        IEnumerable<Type> types = this.GetTypesWith<FactoryMethodDelegateAttribute>(true);
        foreach (var type in types)
        {
            var attribute =
                (FactoryMethodDelegateAttribute)
                type.GetCustomAttributes(typeof(FactoryMethodDelegateAttribute), true).First();

            mappings.Add(attribute.TypeId, attribute.FactoryMethod);
        }

        var message = mappings[Message.MessageType.ChatMsg](buffer);
    }
}

您走的路正确,使用字典是个好主意。 如果反射太慢,则可以使用这样的表达式(我假设您使用MessageTypeAttribute装饰Messages类)。

public class Test
{
 public Test()
  {
     var dict=new Dictionary<MessageType,Func<Buffer,Mesage>>();
     var types=from a in AppDomain.CurrentDomain.GetAssemblies()
         from t in a.GetTypes()
         where t.IsDefined(MessageTypeAttribute, inherit)
         select t;
    foreach(var t in types) {
      var attr = t.GetCustomAttributes(typeof (MessageTypeAttribute), false).First();
       dict[attr.MessageType] = CreateFactory(t);
       }

      var msg=dict[MessageType.Chat](Buf);
  }

 Func<Buffer,Message> CreateFactory(Type t)
 {
      var arg = Expression.Parameter(typeof (Buffer));
        var newMsg = Expression.New(t.GetConstructor(new[] {typeof (Buffer)}),arg);
        return Expression.Lambda<Func<Buffer, Message>>(newMsg, arg).Compile();
}

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM