Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

c# - How can I use Debug.Write with dynamic data?

I am doing some scripting of Adobe InDesign. Their COM implementation is really designed for VB, so it's not rigorous about reporting data types, occasionally necessitating the use of dynamics.

I'm trying to debug a chunk of code that looks like this:

foreach (dynamic pi in current.PageItems)
{
    if (pi is TextFrame)
    {
        var frame = pi as TextFrame;
        var str = frame.Contents.ToString();
        Debug.WriteLine(str);
    }
}

This gives me a RuntimeBinderException like this:

Additional information: Cannot dynamically invoke method 'WriteLine' because it has a Conditional attribute

I get that the problem is that with Conditional attributes, the version of the code that needs to handle the type the dynamic resolves to at runtime might have gotten compiled out, but I'm explicitly converting what I want to debug to a string, so I don't see why this is still happening. How can I work around this problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're being bitten by your use of var here, is my guess.

I'm assuming that Contents is dynamic.

Consider this example:

dynamic d = null;
var s = d.ToString();

s is dynamic not string.

You'll want to cast the object to object before calling ToString, or cast the result of ToString to a string. The point is that at some point, somewhere, you need a cast to get out of the dynamic cycle.

This is how I'd solve it:

string str = ((object)frame.Contents).ToString();
Debug.WriteLine(str);

or

string str = frame.Contents.ToString() as string;
Debug.WriteLine(str);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...