让多个类做很多事情,我必须实例化其中一个类,填充一些属性并调用一个方法。样本将具有以下方法,例如
public class Method100Response201
{
public string R1_01 { get; set; }
public void DoSpecialThing()
{ Console.WriteLine ("Something Blue..}"); }
}
public class Method100Response404
{
public string R2_01 { get; set; }
public void DoSpecialThing()
{ Console.WriteLine ("Something Old..}"); }
}
public class Method110Response200
{
public string R3_01 { get; set; }
public void DoSpecialThing()
{ Console.WriteLine ("Something New..}"); }
}
它们都在同一命名空间中的 Program 类中,我有机制来找出我需要哪个类:
static void Main(string[] args)
{
int[] MethodResponse = DoSomethingHere (23, "something", true);
string DerivedClassName = ResponseModel(MethodResponse[0], MethodResponse[1]);
Console.WriteLine (
"For method " + MethodResponse[0].ToString ()
+ " and response " + MethodResponse[1].ToString ()
+ " you must instantiate Class "
+ DerivedClassName);
Console.ReadKey ();
//how do I do this????
//const string objectToInstantiate = "MyProject.Domain.MyNewTestClass, MyTestProject";
//var objectType = Type.GetType (objectToInstantiate);
//dynamic instantiatedObject = Activator.CreateInstance (objectType) as ITestClass;
// set a property value
//instantiatedObject.Name = DerivedClassName;
// get a property value
//string name = instantiatedObject.Name;
// call a method - output "Something Blue.."
//Console.Write (instantiatedObject.DoSpecialThing ());
}
public static int[] DoSomethingHere (int param1, string param2, bool whatever)
{
int firstInt = 0; int secondInt = 0;
//
//lots of work here, I end up with method and selector..
//
firstInt = 100;
secondInt = 201;
return new int[] { firstInt, secondInt };
}
public static string ResponseModel(int method, int response)
{
string returnClass = String.Empty;
switch (method)
{
case 100:
if (response == 201)
{ Console.WriteLine ("Case 100,201"); returnClass = "Method100Response201"; }
else
{ Console.WriteLine ("Case 100,404"); returnClass = "Method100Response404"; }
break;
case 110:
Console.WriteLine ("Case 100,404"); returnClass = "Method110Response200";
break;
case 120:
// ...
break;
}
return returnClass;
}
我尝试了一种叫做 Activator 的东西,我不是专家,这对我来说真的很重要。有人可以帮我吗? (我根据 SO 中发布的解决方案对我正在尝试的一些代码进行了评论。谢谢)。