让我们假设我有这些课程
Animal
Cat : Animal
Dog : Animal
如果在某个方法中,我有以下内容:
Type animalType = someClass.Animal.GetType();
如何将someClass.Animal
转换为animalType
中包含的任何类型?类似的东西:
var animal = (animalType.Type)someClass.Animal;
答案 0 :(得分:1)
你需要一个通用的方法:
public static class Converter
{
public static T ConvertTo<T>(this object source) where T :class
{
if (source is T)
{
return (T) source;
}
else
{
return null; // or throw exception
}
}
}
然后您可以使用Reflection来调用此方法:
class Animal { }
class Cat : Animal { }
class Dog : Animal
{
public override string ToString()
{
return "I'm a dog!";
}
public bool IsDog { get { return true; } }
}
Animal a = new Dog();
var methodInfo = typeof (Converter)
.GetMethod("ConvertTo", BindingFlags.Static | BindingFlags.Public);
var method = methodInfo.MakeGenericMethod(a.GetType());
var dog = method.Invoke(null, new object[] { a });
Console.WriteLine(dog.ToString());
在这种情况下,它会将I'm a dog
写入控制台。但由于Invoke
方法返回了一个对象,因此您无法访问Dog
的方法或属性。为此,您可以使用动态功能:
dynamic dog = method.Invoke(null, new object[] { a });
Console.WriteLine(dog.IsDog); // true
但是你失去了 type-safety 。
因此,如果您不知道要在编译时转换的类型,则无法使用类型实例直接执行此操作。