在c#中使用对象类型的字符串名称类型转换
问题描述:
我有以下代码,应该很容易遵循
I have the following code, should be easy to follow through
public class Foo
{
public void FooHasAMethod()
{
Console.WriteLine("it is me, foo!!!");
}
}
public class Bar
{
public Foo FooProperty { get; set; }
}
public class FooBar
{
public static void Main()
{
Bar bar = new Bar{ FooProperty = new Foo() };
CallPropertyByName(bar, "Foo");
}
public static void CallPropertyByName(Bar bar, string propertyName)
{
PropertyInfo pi = bar.GetType().GetProperty(propertyName + "Property");
object fooObj = pi.GetValue(bar, null);
((Foo)fooObj).FooHasAMethod(); // this works
/* but I want to use
* ((Type.GetType(propertyName))fooObj).FooHasAMethod(); This line needs fix
* which doesnt work
* Is there a way to type cast using a string name of a object?
* */
}
}
答
Type fooObjType = fooObj.GetType();
MethodInfo method = fooObjType.GetMethod("FooHasAMethod");
method.Invoke(fooObj, new object[0]);