开发者

Dynamic type in method parameter

I am passing in a dynamic type into a method and having some issues running the code. Wondering if you are able to pass a dynamic object into as a parameter using the out keyword.

Below is the code.

dynamic btApp = AutomationFactory.CreateObject("Test.Application");
dynamic btMessages;

dynamic btFormat = btApp.Formats.Open("c:\\Temp/Format1.btw", false, "");
btFormat.SetNamedSubStringValue("testing", "testtest");
btFormat.Print("Job1", true, -1, out btMessages);
btFormat.Close(2);

is开发者_如何学Pythonsue is in the print method. where the last argument is passing in a dynamic object.


When you pass a out parameter to a method with a variable that is of type dynamic the parameter itself must be of type dynamic. The following code is legal:

class Program {
    static void Main(string[] args) {
        dynamic value;
        SomeMethod(out value);
        return;
    }
    static void SomeMethod(out dynamic value) {
        value = "5";
        return;
    }
}

In fact SomeMethod can assign anything to value. When the parameter is not of type dynamic then the compiler attempts to convert before the method call, which is not permitted, so if the parameter in SomeMethod is anything but dynamic, your out of luck.


It depends on what the actual type signature of the Print method is. The dynamic type is represented as object at runtime, so if the Print method takes an out parameter of type object (or dynamic), then it should work.

If the Print method has actual out parameter of some other type, then the actual runtime type used at the side of the caller doesn't match the actual type of the declaration, so it will not work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜