在c#中使用对象类型的字符串名称类型转换 [英] Type casting in c# using the string name of the object type
本文介绍了在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]);
这篇关于在c#中使用对象类型的字符串名称类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文