Note that there are some explanatory texts on larger screens.

plurals
  1. POStrongly-typed property reference to multiple classes with no common interface (C#)
    text
    copied!<p>The <code>System.Windows.Documents</code> namespace includes a number of classes with an <code>Inlines</code> property of type <code>InlineCollection</code>. For example, the <code>Paragraph</code>, <code>Bold</code> and <code>Hyperlink</code> classes all have this property.</p> <p>Each of these classes is decorated with <code>ContentPropertyAttribute</code> ...</p> <pre><code>[ContentPropertyAttribute("Inlines")] public class Paragraph : Block </code></pre> <p>... which means that it is easy enough, using reflection, to detect that a given object exposes this property.</p> <p>However, I need to be able to access this property in a strongly-typed manner across a selection of the types that implement it.</p> <p>I am a little surprised that Microsoft didn't make all these classes implement an "<code>IInlineContainer</code>" interface, which would have made type checking and casting very easy.</p> <p>However, in the absence of such an interface, is there any way to fake this polymorphic functionality, ideally without littering my code with lots of conditions and type checking?</p> <p>Many thanks for your ideas,</p> <p>Tim </p> <p><b>Edit:</b></p> <p>Thanks for your suggestions. A number of people have suggested the idea of a wrapper class, but this is not possible in my situation, as the target objects are not created by my code, but by the other classes in the .NET framework, for example the Xaml parser or the RichTextBox control (in which the containing <code>FlowDocument</code> is being edited).</p> <p><b>Edit 2:</b></p> <p>There have been several great suggestions here and I thank everyone who shared their ideas. The solution I have chosen to implement employs extension methods, which was suggested by @qstarin, although I have refined the concept to suit my needs, as follows:</p> <pre><code>public static InlineCollection GetInlines( this FrameworkContentElement element) { if (element == null) throw new ArgumentNullException("element"); if (element is Paragraph) { return ((Paragraph) element).Inlines; } else if (element is Span) // also catches Bold, Italic, Unerline, Hyperlink { return ((Span)element).Inlines; } else { return null; } } </code></pre> <p>Although this approach requires conditional logic and type casting (which I said I wanted to avoid) the use of extension methods means that it only needs to be implemented in one place, leaving my various calling methods uncluttered.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload