目前,我的代码如下:
static void Main()
{
int whichClass = 0;
if (whichClass == 0)
{
//repeat code
TestAbstract clTest = new ClassA();
clTest.MainFunc();
}
else if (whichClass == 1)
{
//repeat code
TestAbstract clTest = new ClassB();
clTest.MainFunc();
}
else if (whichClass == 10)
{
//repeat code
TestAbstract clTest = new ClassX();
clTest.MainFunc();
}
}
如您所见,我必须在3个不同的类中为初始和调用函数编写代码3次。
我想要的是我们只用动态类调用一次。怎么可能?
答案 0 :(得分:11)
好吧,您可以拥有Dictionary<int, Type>
或Dictionary<int, Func<TestAbstract>
:
var typeMapping = new Dictionary<int, Type>
{
{ 0, typeof(ClassA) },
{ 1, typeof(ClassB) },
{ 10, typeof(ClassX) }
};
...
Type type;
if (typeMapping.TryGetValue(whichClass, out type))
{
TestAbstract test = (TestAbstract) Activator.CreateInstance(type);
test.MainFunc();
}
使用Func<TestAbstract>
可以更灵活地创建TestAbstract
实例,并提供更多的编译时类型安全性,但更加冗长:
var factoryMapping = new Dictionary<int, Func<TestAbstract>>
{
{ 0, () => new ClassA() },
{ 1, () => new ClassB() },
{ 10, () => new ClassX() }
};
...
Func<TestAbstract> factory;
if (factoryMapping.TryGetValue(whichClass, out factory))
{
TestAbstract test = factory();
test.MainFunc();
}
顺便说一下,还不清楚整数值的来源 - 你可能想要一个枚举。哎呀,枚举名称甚至可以是类型的名称:
TestClass whichClass = TestClass.ClassA;
...
Type type = Type.GetType("SomeNamespace." + whichClass);
TestAbstract test = (TestAbstract) Activator.CreateInstance(type);
答案 1 :(得分:5)
您可以创建一个Factory类,它将根据参数返回对象 通过。
public static TestAbstractFactory
{
public static TestAbstract GetTestAbstract(int whichClass)
{
switch(whichClass)
{
case 0:
return new ClassA();
case 1:
return new ClassB();
case 10:
return new ClassX();
default:
return null;
}
}
}
答案 2 :(得分:3)
static void Main()
{
int whichClass = 0;
TestAbstract clTest = null;
if (whichClass == 0)
clTest = new ClassA();
else if (whichClass == 1)
clTest = new ClassB();
else if (whichClass == 10)
clTest = new ClassX();
if(clTest != null)
clTest.MainFunc();
}
答案 3 :(得分:2)
假设ClassA到C派生自TestAbstract并假设MainFunc是TestAbstract上的虚方法,则可以使用以下代码
static void Main()
{
int whichClass = 0; // 0 to 2
Type type = new[] { typeof(ClassA), typeof(ClassB), typeof(ClassC) } [ whichClass ];
TestAbstract clTest = (TestAbstract) Activator.CreateInstance(type);
clTest.MainFunc();
}
答案 4 :(得分:0)
static void Main()
{
int whichClass = 0;
TestAbstract clTest ;
if (whichClass == 0)
{
//repeat code
clTest = new ClassA();
}
else if (whichClass == 1)
{
//repeat code
clTest = new ClassB();
}
else if (whichClass == 10)
{
//repeat code
clTest = new ClassX();
}
clTest.MainFunc();
}
答案 5 :(得分:0)
static void Main()
{ int whichClass = 0; TestAbstract clTest; if (whichClass == 0) { //repeat code clTest = new ClassA(); } else if (whichClass == 1) { //repeat code clTest = new ClassB(); } else if (whichClass == 10) { //repeat code clTest = new ClassX(); } if(clTest != null) clTest.MainFunc(); }
答案 6 :(得分:0)
你可以使用反射。
string whichClass = "className";
Type t = Type.GetType(whichClass);
TestAbstract o = (TestAbstract)Activator.CreateInstance(t);
o.MainFunc();