嗨,我该怎么做呢?
int z = 1;
string one = "pc";
string two = z.ToString();
//what goes here
Console.Write("Host One:\tSent-{0}\tSuccess-{1}\tFail-{2}", xxxxx.numepings, pc1.numepings_s, pc1.numepings_f);
Console.WriteLine();所以在我的代码中,pc1是一个对象的实例,我可以在//what goes here行中使用什么来代替xxxxx,这样我就可以从合并的字符串变量pc和int 1中调用该实例??
发布于 2012-03-26 23:05:25
基本上,你不需要。你可以使用反射,但这不是一个好主意。相反,每当您想要存储对多个对象的引用并通过某种键(无论是索引、名称还是其他什么)对它们进行寻址时,都应该使用集合。
因此,与其拥有:
Foo pc0;
Foo pc1;
Foo pc2;
...您将拥有:
List<Foo> pcs;
...
Foo pc = pcs[z]; 发布于 2012-03-26 23:08:41
查看此处:http://msdn.microsoft.com/en-us/library/1fce0hc8.aspx
// Create an instance of the SomeType class that is defined in this
// assembly.
var oh = Activator.CreateInstanceFrom(Assembly.GetEntryAssembly().CodeBase, one + z /* as a full type name */);
// Call an instance method defined by the SomeType type using this object.
dynamic st = oh.Unwrap();
st.DoSomething(5);你可以这样做来创建一个对象,从它的字符串名-但是你不能没有问题地将它转换为一个特定的类型。
你可以作弊,也可以使用dynamic。
编辑:对不起,这是不太正确的最初-我已经修复了我的例子。
https://stackoverflow.com/questions/9874604
复制相似问题