【问题标题】:C# Automatic find a Children Class by a Unique IDC# 通过唯一 ID 自动查找子类
【发布时间】:2009-08-30 17:32:57
【问题描述】:

我有大约 20 个针对不同消息的课程,而且这个数字还在增长。每个类都有一个唯一的 ID,所以我可以用我自己的序列化方法在 byte[] 上转换类,然后用这个 uniqueID 在我的类上再次转换一个 byte[]。 我所有的消息都是 BaseMessage 类的子类,该类已经正确实现了 uniqueID 生成。

我想要做的是直接找到相应 ID 的类,而不使用 Enum 进行比较。 我对 Enum 的问题是,每次创建新消息类时,Enum 都不会自动更新为我的新 ID。

有没有一种方法可以结合 Attributes 和 Assembly 来做到这一点,比如发现 BaseClass 的所有孩子,然后调用 CustomAtribute?

谢谢!

【问题讨论】:

    标签: c# .net serialization assemblies uniqueidentifier


    【解决方案1】:

    您在正确的道路上 - 这听起来确实是处理它的好方法。您需要将类型的唯一 ID 与序列化值一起存储,以便您可以在反序列化之前读取 ID,以将反序列化器定向到正确的类型。您也可以只存储完全限定的类型名称而不是使用 ID,但这也是一种很好的方法。

    该属性很容易创建:

    class MessageAttribute : Attribute
    {
        public Guid ID; //assuming you want to use a GUID, could be anything
    }
    

    而且使用起来也很简单:

    [Message(ID = new Guid("..."))]
    class SubMessage : BaseMessage
    {
    }
    

    您可以加载给定程序集中的所有类型并快速迭代它们:

    List<Type> messageTypes = new List<Type>();
    
    //get the assembly containing our types
    Assembly messageAssembly = Assembly.Load(...);
    
    //get all the types in the assembly
    Type[] types = messageAssembly.GetTypes();
    foreach(Type type in types)
    {
        //make sure we inherit from BaseMessage
        if(type.IsAssignableFrom(typeof(BaseMessage))
        {
            //check to see if the inherited type has a MessageAttribute
            object[] attribs = type.GetCustomAttribtues(typeof(MessageAttribute), true);
            if(attribs.Length > 0)
            {
                messageTypes.Add(type);
            }
        }
    }
    

    【讨论】:

    • 感谢您的快速答复。你确定这个程序集加载和类型循环很快吗?我需要在我的程序中多次进行此验证。我想我可以在静态时间创建这个列表,然后再使用。
    • @Gustavo 是的,它非常快。您当然是正确的,无论如何它只需要在启动时完成一次。之后,该列表可以在应用程序的整个生命周期内缓存。
    猜你喜欢
    • 2020-02-10
    • 2016-07-04
    • 1970-01-01
    • 1970-01-01
    • 2018-10-12
    • 1970-01-01
    • 2018-12-16
    • 2017-05-31
    • 1970-01-01
    相关资源
    最近更新 更多