如果您使用 .NET 4,这实际上非常简单 =D
dynamic obj = bar;
obj.FooProperty.FooHasAMethod();
但是,如果您只想将结果转换为其他类型,则可以在运行时使用 Convert.ChangeType 方法执行此操作:
object someBoxedType = new Foo();
Bar myDesiredType = Convert.ChangeType(typeof(Bar), someBoxedType) as Bar;
现在,这个与实际类型 Foo 和 Bar 有着很强的联系。但是,您可以通用该方法来获得您想要的:
public T GetObjectAs<T>(object source, T destinationType)
where T: class
{
return Convert.ChangeType(typeof(T), source) as T;
}
然后,您可以像这样调用:
Bar x = GetObjectAs(someBoxedType, new Bar());
SomeTypeYouWant x = GetObjectAs(someBoxedType, Activator.CreateInstance(typeof("SomeTypeYouWant")));
使用激活器,您可以在运行时创建您想要的任何类型。并且泛型方法会被推理欺骗,尝试从 boxedType 转换为运行时类型。
此外,如果您只想对某些动态属性值调用方法,那么最佳实践(imo)就是简单地将其转换为某些所需的对象。
ISomething propValue = obj.GetProperty("FooPropery").GetValue(obj, null) as ISomething;
if(propValue != null)
propValue.FooHasAMethod();