开发者

How to convert value types returned by the MethodInfo.Invoke method, to their proper type?

I'开发者_开发技巧d like to invoke a method that returns a struct, using the MethodInfo.Invoke method. However, the returned variable's type of this metod is object, which cannot be cast to a struct.

(found that, as well as the suggestion to switch from struct to class, here: http://msdn.microsoft.com/en-us/library/b7tch9h0(VS.90).aspx )

So how could I cast the (value) result of the invoked method to it's proper type?

(I've tried simple cast as well, but it threw an InvalidCastException)

Here are some chunks of my code:

public class MyInvokedClass
{
    public struct MyStruct
    { ... };

    public MyStruct InvokedMethod()
    { 
        MyStruct structure;
        ... 
        return structure; 
    }
}

public class MyInvokingClass
{
    // Same structure here
    public struct MyStruct
    { ... };

    static void Main(string[] args)
    { 
        ...
        MethodInfo methodInfo = classType.GetMethod(methodName);
        MyStruct result = (MyStruct)methodInfo.Invoke(classInstance, null); 
        // the line above throws an InvalidCastException
    }
}

Thank you all!


The cast fails because they are different types, more specifically one is MyInvokedClass.MyStruct and the other is MyInvokingClass.MyStruct.

When InvokedMethod gets called the MyStruct refers to the type nested inside the MyInvokedClass, but the when the cast is performed (MyStruct) refers to the type nested inside the MyInvokingClass.

You could use MyInvokedClass.MyStruct inside MyInvokingClassto refer to the correct struct, but even better is just to have one MyStruct type.

You may find useful to read more about declaration space:

C# Basic Concepts—Declarations


You have two different types: MyInvokedClass.MyStruct and MyInvokingClass.MyStruct.

The method you're invoking presumably returns MyInvokedClass.MyStruct and you're attempting to cast it to a MyInvokingClass.MyStruct. You're hitting the InvalidCastException because those are two completely different types.


To solve your problem, move the structure out of the classes:

public struct MyStruct
{ ... };

public class MyInvokedClass
{
    public MyStruct InvokedMethod()
    { 
        MyStruct structure;
        ... 
        return structure; 
    }
}

public class MyInvokingClass
{
    static void Main(string[] args)
    { 
        ...
        MethodInfo methodInfo = classType.GetMethod(methodName);
        MyStruct result = (MyStruct)methodInfo.Invoke(classInstance, null); 
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜