public IParser <T> GetParser <T>() { // attempt to look up the correct parser for type T from the dictionary Type targetType = typeof(T); IParser parser; if (!this._Parsers.TryGetValue(targetType, out parser)) { // no parser was found, so check the target type for a Parser attribute object[] attributes = targetType.GetCustomAttributes(typeof(ParserAttribute), true); if (attributes != null && attributes.Length > 0) { ParserAttribute parserAttribute = (ParserAttribute)attributes[0]; // create an instance of the identified parser parser = (IParser <T>)Activator.CreateInstance(parserAttribute.ParserType); // and add it to the dictionary this._Parsers.Add(targetType, parser); } else { throw new InvalidOperationException(string.Format("Unable to find a parser for the type [{0}].", targetType.Name)); } } return((IParser <T>)parser); }
/// <summary> /// Adds all parsers that implement <see cref="ParserAttribute"/>. /// </summary> private void AddParsersByReflection() { // Find each method with the command attribute then add it to the console commands foreach (MethodInfo method in Assembly.GetCallingAssembly().GetTypes().SelectMany(x => x.GetMethods().Where(y => y.GetCustomAttributes(typeof(ParserAttribute), false).Count() > 0))) { ParserAttribute attribute = (ParserAttribute)method.GetCustomAttributes(typeof(ParserAttribute), false).First(); AddParser(attribute.Target, method); } }
private void InitialParsers() { Type[] types = Assembly.GetExecutingAssembly().GetTypes(); foreach (Type type in types) { if (!type.IsSubclassOf(typeof(PageParser))) { continue; } ParserAttribute attribute = type.GetCustomAttribute <ParserAttribute>(true); if (attribute == null) { continue; } ConstructorInfo cInfo = type.GetConstructor(new[] { typeof(Locale), typeof(int) }); if (cInfo == null) { continue; } PageParser parser = (PageParser)cInfo.Invoke(new object [] { Locale.English, 0 }); if (parser == null) { throw new InvalidOperationException("parser"); } if (m_parsers.ContainsKey(attribute.ParserType)) { Console.WriteLine("There is another parser for ParserType.{0}", attribute.ParserType); continue; } m_parsers[attribute.ParserType] = parser; } }
public DuplicatedParser(ParserAttribute attribute) : base(GetMessage(attribute)) => this.attribute = attribute;