如何使用Reflection来解决这个问题.... (C#/.NET)

Mar*_*_55 -1 .net reflection c#-3.0

我正在开发C#/ .NET 3.5应用程序(并希望继续使用该版本的.NET),并且无法使用Reflection来解决如何解决此问题.我找到了解决方法,但不是"整洁".代码如下,我需要发现所有接口实现,以便将来在添加更多接口实现时,我不需要更改现有代码.

interface Ii { }
class A : Ii { }
class A1 : A { }
class A2 : A { }
class A3 : A { }
class B : Ii { }
class C : Ii{ }
// maybe in future class D : Ii { }
// maybe in future class E : Ii { }

class Helper
{
    static List<Type> GetAllInterfaceImplemenations()
    {// do reflection magic and return ["A1","A2","A3","B","C"] ...
     // I will use this method to fill comboBox-es , create objects factory, etc...
     // there should be no changes if/when in future I add class D etc.
    }
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*Dan 5

试试这个:

public static List<string> GetAllInterfaceImplemenations()
{
    var interfaceType = typeof(Ii);
    var list = new List<string>();
    foreach (var type in Assembly.GetExecutingAssembly().GetTypes())
    {
        if (type.IsClass && interfaceType.IsAssignableFrom(type))
        {
            list.Add(type.Name);
        }
    }

    return list;
}
Run Code Online (Sandbox Code Playgroud)