简体   繁体   English

在运行时将对象转换为另一种类型

[英]Cast object to another type at run time

void A(object o)
{
    ...
    Assembly a = Assembly.LoadFile(...);
    Type t = a.GetType(@"namespace.className");
    MethodInfo mi = t.GetMethod(@"MethodName");
    mi.Invoke(instace, new Object[] {o});
    ....         
}

the method I need to invoke accept another type, I need to cast the object to that type, but, the type is known only at run time, so can I convert/cast object to another type known only at run time ? 我需要调用的方法接受另一种类型,我需要将对象转换为该类型,但是,该类型仅在运行时才知道,因此我可以将对象转换/广播为仅在运行时才知道的另一种吗? I can change only method A. 我只能更改方法A。

thank you. 谢谢。

The Reflection APIs only deal with object references. Reflection API仅处理object引用。 Casting a reference is an operation on that reference. 投射参考是对该参考的操作。 It does not affect the object in any way. 它不会以任何方式影响对象。

For that reason it is not necessary to cast anything here. 因此,没有必要在此处投射任何内容。 Just pass o to Invoke like you are already doing. 就像您已经在做的那样,只需将o传递给Invoke The Reflection API validates the type of o and passes it to the method you want to call. Reflection API会验证o的类型,并将其传递给您要调用的方法。

The MethodInfo.Invoke(object instance, object[] arguments) is dynamic invoke. 所述MethodInfo.Invoke(object instance, object[] arguments)是动态调用。 That means, the casting is made automatically. 也就是说,铸造是自动进行的。 If is thrown InvalidCastException , then you pass the wrong argument or the exception is thrown from inner code and is not caused by object passed to arguments. 如果抛出InvalidCastException ,则您传递了错误的参数,或者异常是从内部代码引发的,并且不是由传递给参数的对象引起的。

This is the code I used when I had several similar messages coming need, that needed different handling. 这是我需要多个类似消息时需要使用不同处理方式的代码。 Ordertype was a Type instance of a custom order object. Ordertype是自定义订单对象的Type实例。

            var _ot = Activator.CreateInstance(ordertype);
            var _otconvert = ordertype.GetMethod("ConvertRequestPayload");

            object[] _params = new object[] {message};

            var objectf = _otconvert.Invoke(_ot, _params);

            var _as = Activator.CreateInstance(servicetype);
            var _method = servicetype.GetMethod("StartProcess");

            var rMessage = _method.Invoke(_as, new object[] {objectf});

Basically Activator is what you need. 基本上需要Activator。 it allows you create objects of required type at runtime. 它允许您在运行时创建所需类型的对象。

我将{object 0}更改为{dynamic 0}并且它起作用了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM