简体   繁体   中英

Cannot implicitly convert type object to string in PrivateObject in C#

From what I read, I can pass in an object for the parameters in a PrivateObject object. The code gives the error in the description.

[TestMethod]
public void TestMethod1()
{
    MessageToSend message = new MessageToSend();
    Sender sender = new Sender(null, null, null);
    var dto = new DateTimeOffset();

    PrivateObject pObj = new PrivateObject(typeof(Sender));

    Object[] args = new Object[] { "Hello", "Marc", "Perry", dto };
    string result = pObj.Invoke("ParseBody", args);
}

Error

Cannot implicitly convert type object to string

The method it is calling is

private string ParseBody(string sBody, string sFirstName, string sLastName, DateTimeOffset? tSourceTimeInfo)

The PrivateObject.Invoke method takes object[] arguments and returns object , so it can cope with most things. The compiler doesn't trust object to be a string , as while that may be true at runtime, it isn't true for the compiler.

So... you'll need to cast explicitly:

string result = (string)pObj.Invoke("ParseBody", args);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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