在 c# 中,我想找到一种方法来执行以下操作:
(cast_by_variable)some_class.some_method();
所以,我想以某种方式确定子类的类型,将信息存储在变量中,然后在父类使用强制转换时使用它。
Object obj;
if (some_class is Class1)
{
obj = (Class1)some_class;
// do something with obj
}
投射对象不会改变它的类型,所以你总是可以用
some_class.GetType();
Type type = some_class.GetType();
c# 中没有像您建议的那样直接运行时强制转换,但有解决此问题的方法。您可以执行以下操作:
Type t = some_class_obj.GetType();
object result =t.GetMethod("some_method").Invoke(some_class_object,new object[]{parameter1,parameter2});