![](/img/trans.png)
[英]How to instantiate an interface object with implementation that is passed in to current method in C#?
[英]How to find an implementation of a C# interface in the current assembly with a specific name?
我有一個名為IStep
的接口可以進行一些計算(參見“ 名詞王國中的執行 ”)。 在運行時,我想按類名選擇適當的實現。
// use like this: IStep step = GetStep(sName);
你的問題很混亂......
如果要查找實現IStep的類型,請執行以下操作:
foreach (Type t in Assembly.GetCallingAssembly().GetTypes())
{
if (!typeof(IStep).IsAssignableFrom(t)) continue;
Console.WriteLine(t.FullName + " implements " + typeof(IStep).FullName);
}
如果您已經知道所需類型的名稱,請執行此操作
IStep step = (IStep)Activator.CreateInstance(Type.GetType("MyNamespace.MyType"));
如果實現具有無參數構造函數,則可以使用System.Activator類執行此操作。 除了類名,您還需要指定程序集名稱:
IStep step = System.Activator.CreateInstance(sAssemblyName, sClassName).Unwrap() as IStep;
http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx
基於其他人的指出,這就是我最后寫的:
/// /// Some magic happens here: Find the correct action to take, by reflecting on types /// subclassed from IStep with that name. /// private IStep GetStep(string sName) { Assembly assembly = Assembly.GetAssembly(typeof (IStep)); try { return (IStep) (from t in assembly.GetTypes() where t.Name == sName && t.GetInterface("IStep") != null select t ).First().GetConstructor(new Type[] {} ).Invoke(new object[] {}); } catch (InvalidOperationException e) { throw new ArgumentException("Action not supported: " + sName, e); } }
Well Assembly.CreateInstance似乎是要走的路 - 唯一的問題是它需要類型的完全限定名,即包括命名空間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.