通过反射获取对象(Get object by reflection)

我正在寻找c#这样的机制:

Car car1; Car car2; Car car = (Car)SomeMechanism.Get("car1");

car1和car2是田野

所以我想用反射来获得一些对象,而不是键入:/我怎样才能在C#中做到这一点?

I'm looking for mechanism in c# works like that:

Car car1; Car car2; Car car = (Car)SomeMechanism.Get("car1");

car1 and car2 are fields

So I want to get some object with reflection, not type :/ How can I do it in c# ?

最满意答案

局部变量不可能,但如果你有一个字段,你可以这样做

class Foo{ public Car car1; public Car car2; }

你可以做

object fooInstance = ...; Car car1 = (Car)fooInstance.GetType().GetField("car1").GetValue(fooInstance);

It's not possible for local variables but If you have a field, you can do

class Foo{ public Car car1; public Car car2; }

you can do

object fooInstance = ...; Car car1 = (Car)fooInstance.GetType().GetField("car1").GetValue(fooInstance);

更多推荐