Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>Edited</strong> With .NET 3.5 using LinFu You may use LinFu instead of Castle. However, you would be using reflection anyway, both with Castle's and with Linfu's DynamicProxy, only hidden in the guts of the libraries instead of being exposed in your code. So if your requirement to avoid the use of reflection is out of performance concerns, you wouldn't really avoid it with this solution. In that case I would personally choose Orsol's solution.</p> <p>However: here's an example with LinFu's ducktyping.</p> <pre><code>public interface ISomeType { object Value{get; set;} } public class SomeType1 { public int Value { get; set; } } public class SomeType2 { public string Value { get; set; } } public class SomeTypeWrapperFactory { public static ISomeType CreateSomeTypeWrapper(object aSomeType) { return aSomeType.CreateDuck&lt;ISomeType&gt;(); } } class Program { public static void Main(string[] args) { var someTypes = new object[] { new SomeType1() {Value=1}, new SomeType2() {Value="test"} }; foreach(var o in someTypes) { Console.WriteLine(SomeTypeWrapperFactory.CreateSomeTypeWrapper(o).Value); } Console.ReadLine(); } } </code></pre> <p>Since you don't know the type of the SomeType's until runtime, I would not use mixins, but the visitor pattern (I know this doesn't answer the question on how to use mixins for this, but I just thought I'd throw in my 2 cents).</p> <p><strong>With .NET 4 using dynamic</strong> See <a href="http://code.logos.com/blog/2010/03/the_visitor_pattern_and_dynamic_in_c_4.html" rel="nofollow">Bradley Grainger's post here</a> on using c#4's dynamic keyword to implement the visitor pattern. In your case, reading all the "Value" properties from your dictionary of SomeType's could work like this:</p> <pre><code>public class SomeType1 { public int Value { get; set; } } public class SomeType2 { public string Value { get; set; } } public class SomeTypeVisitor { public void VisitAll(object[] someTypes) { foreach(var o in someTypes) { // this should be in a try-catch block Console.WriteLine(((dynamic) o).Value); } } } class Program { public static void Main(string[] args) { var someTypes = new object[] { new SomeType1() {Value=1}, new SomeType2() {Value="test"} }; var vis = new SomeTypeVisitor(); vis.VisitAll(someTypes); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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