将VB转换为C#'GetCustomAttribute'

时间:2014-08-19 18:41:03

标签: c# vb.net

我想在C#中翻译这个功能;

Private Shared Sub GetTypes(ByVal AssemblyName As String)
        Dim ass As Assembly = Assembly.Load(AssemblyName)
        For Each value As Type In ass.GetTypes()
            Dim methods() As MethodInfo = value.GetMethods()
            Dim InstanceType As MessageHandler
            For Each method As MethodInfo In methods
                [color=#40BF00]InstanceType = System.Attribute.GetCustomAttribute(method, GetType(MessageHandler), False)[/color]
                If InstanceType Is Nothing Then
                    Continue For
                End If
                Dim pack As DofusNetworkMessage = DirectCast(Activator.CreateInstance(InstanceType.MessageType), DofusNetworkMessage)
                Dim instance As InstanceInfo = New InstanceInfo(pack.ProtocolID, InstanceType.MessageType, method)
                Func.Add(New KeyValuePair(Of Integer, InstanceInfo)(pack.ProtocolID, instance))
            Next
        Next
    End Sub

我获得了这个

private static void InitializeFrames()
    {
        Assembly assembly = Assembly.Load("SmartBot.Engine");
        foreach (Type type in assembly.GetTypes())
        {
            MessageHandler InstanceType = null;

            foreach (MethodInfo Method in type.GetMethods())
            {
                [color=#FF0000]InstanceType = System.Attribute.GetCustomAttribute(Method, typeof(MessageHandler), false);[/color]
                if (InstanceType == null)
                {
                    continue;
                }
                NetworkMessage pack = (NetworkMessage)Activator.CreateInstance(InstanceType.MessageType);
                InstanceInfo instance = new InstanceInfo(pack.ProtocolId, InstanceType.MessageType, Method);
                Handles.Add(new KeyValuePair<int, InstanceInfo>(pack.ProtocolId, instance));
            }

        }
    }

我对此行有疑问:

InstanceType = System.Attribute.GetCustomAttribute(Method, typeof(MessageHandler), false);

我收到此错误; 无法隐式转换类型&#39;系统。属性&#39; in&#39; SmartBot。发动机。帧。 MessageHandler&#39;。存在显式转换(是否缺少转换?)

你能帮助我吗?

2 个答案:

答案 0 :(得分:0)

你只需要投射到MessageHandler

InstanceType = (MessageHandler)System.Attribute.GetCustomAttribute(Method, typeof(MessageHandler), false);

错误消息的这部分提示:存在显式转换(是投射缺失?

答案 1 :(得分:0)

异常消息告诉您,您无法将Attribute隐式转换为MessageHandlerSystem.Attribute.GetCustomAttribute函数返回Attribute - 您需要明确转换为MessageHandler

InstanceType = (MessageHandler)System.Attribute.GetCustomAttribute(Method, typeof(MessageHandler), false);