Agg*_*sor 1 c# static dictionary
在我之前提出的一个问题中我不清楚,所以我会更加明确.
有没有办法将静态类放在字典中,以便可以调用其函数?如果这是不可能的,那么不使用您可以建议的实例的最佳替代方案是什么?
以下是我想要使用它的方法:
static class MyStatic : IInterface
{
static void Do(){}
}
static class MyStatic2 : IInterface
{
static void Do(){}
}
class StaticMap
{
static Dictionary<Type,IInterface.class> dictionary = new Dictionary<Type,IInterface.class>
{
{Type.1, MyStatic}
{Type.2, MyStatic2}
};
}
// Client Code
class ClientCode
{
void Start()
{
StaticMap.dictionary[Type.1].Do();
}
}
Run Code Online (Sandbox Code Playgroud)
有一些基本原因导致您无法直接执行此操作:
由于您的签名对于每个静态方法都是相同的,因此您可以Action在字典中存储一个:
static Dictionary<Type,Action> dictionary = new Dictionary<Type,Action>
{
{Type.1, MyStatic.Do}
{Type.2, MyStatic2.Do}
};
Run Code Online (Sandbox Code Playgroud)
然后你可以Action直接打电话:
void Start()
{
StaticMap.dictionary[Type.1]();
}
Run Code Online (Sandbox Code Playgroud)
它有点重复,因为你必须在字典中指定方法名称,但它是类型安全的.