public void TestCtorDelegateFromConstructorInfo() { Type type = typeof(TestClass); ConstructorInfo method0 = type.GetConstructor(Type.EmptyTypes); ConstructorInfo method = type.GetConstructor(new Type[] { typeof(string) }); ConstructorInfo method2 = type.GetConstructor(new Type[] { typeof(string), typeof(int) }); // 普通的构造函数。 Assert.AreEqual("NoParam", method0.CreateDelegate <Func <TestClass> >()().Text); Assert.AreEqual("NoParam", ((TestClass)method0.CreateDelegate <Func <object> >()()).Text); Assert.AreEqual(null, method0.CreateDelegate <Func <string, object> >(false)); Assert.AreEqual(null, method0.CreateDelegate <Func <int> >(false)); Assert.AreEqual("Test1", method.CreateDelegate <Func <string, TestClass> >()("Test1").Text); Assert.AreEqual("Test2", method.CreateDelegate <Func <object, TestClass> >()("Test2").Text); Assert.AreEqual(null, method.CreateDelegate <Func <string, string> >(false)); Assert.AreEqual("Test3_10", method2.CreateDelegate <Func <string, int, TestClass> >()("Test3", 10).Text); Assert.AreEqual("Test4_10", method2.CreateDelegate <Func <string, ulong, TestClass> >()("Test4", 10UL).Text); Assert.AreEqual("Test5_10", method2.CreateDelegate <Func <string, short, TestClass> >()("Test5", (short)10).Text); Assert.AreEqual(null, method2.CreateDelegate <Func <string, string, TestClass> >(false)); // 通用构造函数。 Assert.AreEqual("NoParam", ((TestClass)method0.CreateDelegate()()).Text); Assert.AreEqual("Test6", ((TestClass)method.CreateDelegate()("Test6")).Text); Assert.AreEqual("Test7_20", ((TestClass)method2.CreateDelegate()("Test7", 20)).Text); AssertExt.ThrowsException(() => method0.CreateDelegate()("more args"), typeof(TargetParameterCountException)); AssertExt.ThrowsException(() => method.CreateDelegate()(), typeof(TargetParameterCountException)); }
public static void Initialize() { Assembly asm = Assembly.GetAssembly(typeof(MessageInitializer)); foreach (Type type in asm.GetTypes().Where(x => x.IsSubclassOf(typeof(BaseMessage)))) { var fieldId = type.GetField("Id"); if (fieldId != null) { var id = (int)fieldId.GetValue(type); ConstructorInfo ctor = type.GetConstructor(Type.EmptyTypes); if (ctor == null) { throw new Exception( string.Format("'{0}' doesn't implemented a parameterless constructor", type)); } var deleg = ctor.CreateDelegate <Func <BaseMessage> >(); MessageDefinition message; if (!MessagesDefinitions.TryGetValue(id, out message)) { MessagesDefinitions.Add(id, new MessageDefinition(id, type, deleg)); } } } }
public ObjectConverter(JsonSerializerOptions options) { _objectMapping = options.GetObjectMappingRegistry().Lookup <T>(); _memberConverters = new Lazy <MemberConverters>(() => MemberConverters.Create(options, _objectMapping)); _isInterfaceOrAbstract = typeof(T).IsInterface || typeof(T).IsAbstract; _isStruct = typeof(T).IsStruct(); if (!_isInterfaceOrAbstract && _objectMapping.CreatorMapping == null && !_isStruct) { ConstructorInfo defaultConstructorInfo = typeof(T).GetConstructor( BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null); if (defaultConstructorInfo == null) { throw new JsonException($"Cannot find a default constructor on type {typeof(T)}"); } _constructor = defaultConstructorInfo.CreateDelegate <T>(); } _discriminatorConvention = options.GetDiscriminatorConventionRegistry().GetConvention(typeof(T)); _referenceHandling = _isStruct ? ReferenceHandling.Default : options.GetReferenceHandling(); }
public static void Initialize() { Assembly asm = Assembly.GetAssembly(typeof(ProtocolManager)); foreach (Type type in asm.GetTypes()) { if (type.Namespace == null || !type.Namespace.Contains("Protocol.Network.Types")) { continue; } FieldInfo field = type.GetField("ProtocolId"); if (field != null) { int id = (int)(field.GetValue(type)); types.Add((short)id, type); ConstructorInfo ctor = type.GetConstructor(Type.EmptyTypes); if (ctor == null) { throw new Exception(string.Format("'{0}' doesn't implemented a parameterless constructor", type)); } typesConstructors.Add((short)id, ctor.CreateDelegate <Func <object> >()); } } Console.WriteLine(string.Format("<{0}> type(s) loaded.", types.Count)); }
/// <summary> /// Initializes this instance. /// </summary> public static void Initialize() { Assembly asm = Assembly.GetAssembly(typeof(Version)); foreach (Type type in asm.GetTypes()) { FieldInfo field = type.GetField("Id"); if (field != null) { // le cast uint est obligatoire car l'objet n'a pas de type short id = (short)field.GetValue(type); m_types.Add(id, type); ConstructorInfo ctor = type.GetConstructor(Type.EmptyTypes); if (ctor == null) { throw new Exception(string.Format("'{0}' doesn't implemented a parameterless constructor", type)); } m_typesConstructors.Add(id, ctor.CreateDelegate <Func <object> >()); } } }
protected static T TryParse <T> (ISyntaxNode parent, ref string Input) where T : ISyntaxNode { // If the given constructor is not cached, do it... if (!Constructors.ContainsKey(typeof(T))) { ConstructorInfo constr = typeof(T).GetConstructor(new Type[] { typeof(ISyntaxNode), typeof(string).MakeByRefType() }); if (constr == null) { throw new ArgumentException("Given type has no default ISyntaxNode constructor (with ISyntaxNode and ref string parameters)."); } Constructors.Add(typeof(T), constr.CreateDelegate(typeof(SyntaxNodeConstructor <T>))); } try { SyntaxNodeConstructor <T> del = (SyntaxNodeConstructor <T>)Constructors[typeof(T)]; string tmp = Input; T node = del(parent, ref tmp); Input = tmp; // Update Input string... return(node); } catch (ParseException) { return(null); } }
/// <summary> /// Initializes this instance. /// </summary> public static void Initialize() { Assembly asm = Assembly.GetAssembly(typeof(MessageReceiver)); foreach (Type type in asm.GetTypes()) { var fieldId = type.GetField("Id"); if (fieldId != null) { var id = (uint)fieldId.GetValue(type); if (Messages.ContainsKey(id)) { throw new AmbiguousMatchException( string.Format( "MessageReceiver() => {0} item is already in the dictionary, old type is : {1}, new type is {2}", id, Messages[id], type)); } Messages.Add(id, type); ConstructorInfo ctor = type.GetConstructor(Type.EmptyTypes); if (ctor == null) { throw new Exception( string.Format("'{0}' doesn't implemented a parameterless constructor", type)); } Constructors.Add(id, ctor.CreateDelegate <Func <Message> >()); } } }
public static void InitializeMessages() { var assembly = Assembly.GetAssembly(typeof(MessageReceiver)); foreach (var type in assembly.GetTypes().Where(entry => entry.IsSubclassOf(typeof(NetworkMessage)))) { var property = type.GetProperty("Id"); if (property != null) { uint num = (uint)property.GetValue(Activator.CreateInstance(type), null); if (MessageReceiver.Messages.ContainsKey(num)) { throw new AmbiguousMatchException( $"MessageReceiver() => {num} item is already in the dictionary, old type is : {MessageReceiver.Messages[num]}, new type is {type}"); } MessageReceiver.Messages.Add(num, type); ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes); if (constructor == null) { throw new Exception($"'{type}' doesn't implemented a parameterless constructor"); } MessageReceiver.Constructors.Add(num, constructor.CreateDelegate <Func <NetworkMessage> >()); } } }
static DataCenterTypeManager() { Assembly asm = Assembly.GetAssembly(typeof(DataCenterTypeManager)); foreach (Type type in asm.GetTypes()) { if (type.Namespace == null || !type.Namespace.StartsWith(typeof(DataCenterTypeManager).Namespace)) { continue; } if ((type.Name == "IDataCenter") || (type.Name == "DataCenterTypeManager")) { continue; } m_Types.Add(type.Name, type); ConstructorInfo ctor = type.GetConstructor(Type.EmptyTypes); if (ctor == null) { throw new Exception(string.Format("'{0}' doesn't implemented a parameterless constructor", type)); } m_TypesConstructors.Add(type.Name, ctor.CreateDelegate <Func <object> >()); } }
static ProtocolTypeManager() { Assembly asm = Assembly.GetAssembly(typeof(ProtocolTypeManager)); foreach (Type type in asm.GetTypes()) { if (type.Namespace == null || !type.Namespace.StartsWith(typeof(ProtocolTypeManager).Namespace)) { continue; } FieldInfo field = type.GetField("ID"); if (field != null) { // le cast uint est obligatoire car l'objet n'a pas de type short id = (short)(field.GetValue(type)); m_types.Add(id, type); ConstructorInfo ctor = type.GetConstructor(Type.EmptyTypes); if (ctor == null) { throw new Exception(string.Format("'{0}' doesn't implemented a parameterless constructor", type)); } //m_typesConstructors.Add(id, ConstructorHelper.CreateDelegate(ctor, type)<Func<object>>(); m_typesConstructors.Add(id, ctor.CreateDelegate <Func <object> >()); } } }
public static void Initialize() { Assembly asm = Assembly.GetAssembly(typeof(ProtocolTypeManager)); foreach (Type type in asm.GetTypes()) { if (type.Namespace == null || !type.Namespace.StartsWith(typeof(AmaknaProxy.API.Protocol.Types.GameServerInformations).Namespace)) { continue; } FieldInfo field = type.GetField("Id"); if (field != null) { // le cast uint est obligatoire car l'objet n'a pas de type short id = (short)(field.GetValue(type)); types.Add(id, type); ConstructorInfo ctor = type.GetConstructor(Type.EmptyTypes); if (ctor == null) { throw new System.Exception(string.Format("'{0}' doesn't implemented a parameterless constructor", type)); } typesConstructors.Add(id, ctor.CreateDelegate <Func <object> >()); } } }
/// <summary> /// Initialize the SSync Library (Messages and Protocol) and call OnProtocolLoaded(); /// </summary> /// <param name="messagesAssembly"></param> /// <param name="handlersAssembly"></param> public static void Initialize(Assembly messagesAssembly, Assembly handlersAssembly) { foreach (var type in messagesAssembly.GetTypes().Where(x => x.IsSubclassOf(typeof(Message)))) { FieldInfo field = type.GetField("Id"); if (field != null) { ushort num = (ushort)field.GetValue(type); if (Messages.ContainsKey(num)) { throw new AmbiguousMatchException(string.Format("MessageReceiver() => {0} item is already in the dictionary, old type is : {1}, new type is {2}", num, Messages[num], type)); } Messages.Add(num, type); ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes); if (constructor == null) { throw new Exception(string.Format("'{0}' doesn't implemented a parameterless constructor", type)); } Constructors.Add(num, constructor.CreateDelegate <Func <Message> >()); } } foreach (var item in handlersAssembly.GetTypes()) { foreach (var subItem in item.GetMethods()) { var attribute = subItem.GetCustomAttribute(typeof(MessageHandlerAttribute)); if (attribute != null) { ParameterInfo[] parameters = subItem.GetParameters(); Type methodParameters = subItem.GetParameters()[0].ParameterType; if (methodParameters.BaseType != null) { try { Delegate target = subItem.CreateDelegate(HandlerMethodParameterTypes); FieldInfo field = methodParameters.GetField("Id"); Handlers.Add((ushort)field.GetValue(null), target); } catch { throw new Exception("Cannot register " + subItem.Name + " has message handler..."); } } } } } Initialized = true; if (OnProtocolLoaded != null) { OnProtocolLoaded(Messages.Count, Handlers.Count); } }
/// <summary> /// Initializes this instance. /// </summary> public static void Initialize() { Assembly asm = Assembly.GetAssembly(typeof(MessageReceiver)); foreach (Type type in asm.GetTypes().Where(x => x.IsSubclassOf(typeof(Message)))) { var fieldId = type.GetField("Id"); if (fieldId != null) { var id = (uint)fieldId.GetValue(type); var @override = type.GetCustomAttribute <OverrideMessageAttribute>() != null; ConstructorInfo ctor = type.GetConstructor(Type.EmptyTypes); if (ctor == null) { throw new Exception( string.Format("'{0}' doesn't implemented a parameterless constructor", type)); } var deleg = ctor.CreateDelegate <Func <Message> >(); MessageDefinition message; if (MessagesDefinitions.TryGetValue(id, out message)) { if (!message.Override && !@override) { throw new AmbiguousMatchException( string.Format( "MessageReceiver() => {0} item is already in the dictionary, old type is : {1}, new type is {2} (use OverrideMessage attribute)", id, MessagesDefinitions[id], type)); } else if (@override && message.Override) { throw new Exception( string.Format("MessageReceiver() => {0} and {1} override both the same message (id:{2})", message.MessageType, type, id)); } else if (@override) { MessagesDefinitions[id] = new MessageDefinition(id, type, deleg, true); } } else { MessagesDefinitions.Add(id, new MessageDefinition(id, type, deleg, @override)); } } } }
public static void Initialize() { foreach (Type type in Assembly.GetAssembly(typeof(ProtocolTypeManager)).GetTypes()) { if ((type.Namespace == null ? 0 : (type.Namespace.StartsWith(typeof(GameServerInformations).Namespace) ? 1 : 0)) != 0) { FieldInfo field = type.GetField("Id"); if (field != (FieldInfo)null) { uint key = (uint)field.GetValue((object)type); ProtocolTypeManager.types.Add(key, type); ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes); int num = constructor == (ConstructorInfo)null ? 1 : 0; ProtocolTypeManager.typesConstructors.Add(key, constructor.CreateDelegate <Func <object> >()); } } } }
public static void Initialize() { Assembly assembly = Assembly.GetAssembly(typeof(Version)); foreach (var type in assembly.GetTypes().Where(x => !x.IsSubclassOf(typeof(Message)))) { FieldInfo field = type.GetField("Id"); if (field != null) { short key = (short)field.GetValue(type); ProtocolTypeManager.m_types.Add(key, type); ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes); if (constructor == null) { throw new Exception(string.Format("'{0}' doesn't implemented a parameterless constructor", type)); } ProtocolTypeManager.m_typesConstructors.Add(key, constructor.CreateDelegate <Func <object> >()); } } }
public static void Initialize() { Assembly asm = Assembly.GetAssembly(typeof(ISCMessage)); foreach (Type type in asm.GetTypes()) { if (type.Namespace == null || !type.Namespace.Contains("Protocol.ISC")) { continue; } FieldInfo fieldId = type.GetField("Id"); if (fieldId != null) { var id = (uint)fieldId.GetValue(type); if (m_messages.ContainsKey(id)) { throw new AmbiguousMatchException( string.Format( "MessageReceiver() => {0} item is already in the dictionary, old type is : {1}, new type is {2}", id, m_messages[id], type)); } m_messages.Add(id, type); ConstructorInfo ctor = type.GetConstructor(Type.EmptyTypes); if (ctor == null) { continue; } m_constructors.Add(id, ctor.CreateDelegate <Func <ShadowEmu.Common.Network.ISCMessage> >()); } } m_logger.Debug(string.Format("<{0}> ISCmessage(s) loaded.", m_messages.Count)); }
public static void Initialize() { foreach (Type type in Assembly.GetAssembly(typeof(MessageReceiver)).GetTypes()) { if (type.IsSubclassOf(typeof(NetworkMessage))) { FieldInfo field = type.GetField("Id"); if (field != (FieldInfo)null) { uint key = (uint)field.GetValue((object)type); if (MessageReceiver.m_messages.ContainsKey(key)) { throw new AmbiguousMatchException(string.Format("MessageReceiver() => {0} item is already in the dictionary, old type is : {1}, new type is {2}", (object)key, (object)MessageReceiver.m_messages[key], (object)type)); } MessageReceiver.m_messages.Add(key, type); ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes); int num = constructor == (ConstructorInfo)null ? 1 : 0; MessageReceiver.m_constructors.Add(key, constructor.CreateDelegate <Func <NetworkMessage> >()); } } } }
public static void Initialize() { Assembly asm = typeof(Protocol.Network.Messages.Handshake.ProtocolRequired).GetTypeInfo().Assembly; foreach (Type type in asm.GetTypes()) { if (type.Namespace == null || !type.Namespace.Contains("Network.Messages")) { continue; } FieldInfo fieldId = type.GetField("ProtocolId"); if (fieldId != null) { var id = (uint)fieldId.GetValue(type); if (m_messages.ContainsKey(id)) { throw new AmbiguousMatchException( string.Format( "MessageReceiver() => {0} item is already in the dictionary, old type is : {1}, new type is {2}", id, m_messages[id], type)); } m_messages.Add(id, type); ConstructorInfo ctor = type.GetConstructor(Type.EmptyTypes); if (ctor == null) { continue; } m_constructors.Add(id, ctor.CreateDelegate <Func <NetworkMessage> >()); } } Console.WriteLine(string.Format("<{0}> message(s) loaded.", m_messages.Count)); }
public static void Initialize() { Assembly assembly = Assembly.GetAssembly(typeof(MessageReceiver)); foreach (var type in assembly.GetTypes().Where(x => x.IsSubclassOf(typeof(Message)))) { FieldInfo field = type.GetField("Id"); if (field != null) { ushort num = (ushort)field.GetValue(type); if (MessageReceiver.Messages.ContainsKey(num)) { throw new AmbiguousMatchException(string.Format("MessageReceiver() => {0} item is already in the dictionary, old type is : {1}, new type is {2}", num, MessageReceiver.Messages[num], type)); } MessageReceiver.Messages.Add(num, type); ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes); if (constructor == null) { throw new Exception(string.Format("'{0}' doesn't implemented a parameterless constructor", type)); } MessageReceiver.Constructors.Add(num, constructor.CreateDelegate <Func <Message> >()); } } }
/// <param name="messagesAssembly"></param> /// <param name="handlersAssembly"></param> public static void Initialize(Assembly messagesAssembly, Assembly handlersAssembly, bool showProtocolMessages) { ShowProtocolMessage = showProtocolMessages; foreach (var type in messagesAssembly.GetTypes().Where(x => x.IsSubclassOf(typeof(Message)))) { FieldInfo numField = type.GetField(ID_MESSAGE_FIELD_NAME); FieldInfo channelField = type.GetField(CHANNEL_MESSAGE_FIELD_NAME); if (numField != null) { PacketCmd num = (PacketCmd)numField.GetValue(type); Channel channel = (Channel)channelField.GetValue(type); ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes); if (constructor == null) { throw new Exception(string.Format("'{0}' doesn't implemented a parameterless constructor", type)); } if (Messages.ContainsKey(num)) { Messages[num].Add(channel, type); } else { Messages.Add(num, new Dictionary <Channel, Type>() { { channel, type } }); } Func <Message> func = constructor.CreateDelegate <Func <Message> >(); if (Constructors.ContainsKey(num)) { Constructors[num].Add(channel, func); } else { var dic = new Dictionary <Channel, Func <Message> >() { { channel, func } }; Constructors.Add(num, dic); } } } foreach (var item in handlersAssembly.GetTypes()) { foreach (var subItem in item.GetMethods()) { var attribute = subItem.GetCustomAttribute(typeof(MessageHandlerAttribute)); if (attribute != null) { ParameterInfo[] parameters = subItem.GetParameters(); Type methodParameters = subItem.GetParameters()[0].ParameterType; if (methodParameters.BaseType != null) { try { Delegate target = subItem.CreateDelegate(HandlerMethodParameterTypes); FieldInfo field = methodParameters.GetField(ID_MESSAGE_FIELD_NAME); Handlers.Add((PacketCmd)field.GetValue(null), target); } catch { throw new Exception("Cannot register " + subItem.Name + " has message handler..."); } } } } } if (ShowProtocolMessage) { logger.Write(MessageCount + " Message(s) Loaded | " + Handlers.Count + " Handler(s) Loaded"); } }
public CreatorMapping(IObjectMapping objectMapping, ConstructorInfo constructorInfo) { _objectMapping = objectMapping; _delegate = constructorInfo.CreateDelegate(); _parameters = constructorInfo.GetParameters(); }
public static void SpeedTest() { const int Num = 1000000; TimeSpan t1 = new TimeSpan(); TimeSpan t2 = new TimeSpan(); DateTime start; Console.WriteLine("Running test 1: constructor call"); Type t = typeof(IntegerConstant); ConstructorInfo constr = t.GetConstructor(new Type[] { typeof(ISyntaxNode), typeof(string).MakeByRefType() }); ISyntaxNode.SyntaxNodeConstructor <IntegerConstant> del = (ISyntaxNode.SyntaxNodeConstructor <IntegerConstant>)constr.CreateDelegate(typeof(ISyntaxNode.SyntaxNodeConstructor <IntegerConstant>));; if (constr == null) { Console.WriteLine("No constructor found"); } else { start = DateTime.Now; for (int i = 0; i < Num; i++) { String test = "1421"; try { del(null, ref test); } catch (ParseException) { } } t2 = DateTime.Now - start; } Console.WriteLine("Running test 2: static function"); start = DateTime.Now; for (int i = 0; i < Num; i++) { String test = "1421"; IntegerConstant.Parse(null, ref test); } t1 = DateTime.Now - start; Console.WriteLine("Test 1: " + t1); Console.WriteLine("Test 2: " + t2); Console.ReadKey(); }