简体   繁体   English

调用存在于多个命名空间中的相同方法

[英]call same method that exists in multiple namespaces

this code works for me but there must be a better way to accomplish the same thing.这段代码对我有用,但必须有更好的方法来完成同样的事情。 The method Search exists in multiple namespaces.方法 Search 存在于多个命名空间中。 the correct namespace to use depends on code that is irrelevant just like some of the other code displayed.要使用的正确命名空间取决于不相关的代码,就像显示的其他一些代码一样。 any thoughts on rewritting this better?关于重写这个更好的任何想法?

example namespaces used使用的示例命名空间

  • MTG.Sites.Test1 MTG.Sites.Test1

  • MTG.Sites.Test2 MTG.Sites.Test2

     static public async Task<List<Card>> Search(string sNamespace) { List<Card> rawCards = null; try { Type t = Assembly.GetExecutingAssembly().GetType($"MTG.Sites.{sNamespace}"); if (t != null) { dynamic classInstance = Activator.CreateInstance(t); rawCards = await classInstance.Search(httpClient); } } catch(Exception ex) { log.Error(ex); } return rawCards; }

the code i want to improve is the use of Assembly.GetExecutingAssembly().GetType("");我要改进的代码是使用 Assembly.GetExecutingAssembly().GetType("");

the short answer is to use AutoFac.简短的回答是使用 AutoFac。 the longer answer is a complete rewrite of how the code is used.更长的答案是完全重写代码的使用方式。 i essentially need to register each Search class that exists in each Namespace that contains one.我基本上需要注册每个包含一个的命名空间中存在的每个搜索类。 then using the AutoFac examples (AttributeMetadataExample & AspNetCoreExample), i was able to eliminate the need for reflection to find the Search method in each Namespace (passed as a string to GetType)然后使用 AutoFac 示例(AttributeMetadataExample 和 AspNetCoreExample),我能够消除在每个命名空间中查找 Search 方法的反射需要(作为字符串传递给 GetType)

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

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