mercredi 1 novembre 2017

Using runtime-created delegates and objects

I have repeatedly struggled with this general concept so it's time to reach out. I have a LINQ query that selects a list of strings from SQL, then calls Select and supplies a static method that ingests a string and returns an object:

MyDataContext context = new MyDataContext();
var list = (
    from t in context.GetTable<FooTable>()
    where t.FooType = userProvidedString
    select t.SomeColumn).ToList()
        .Select(colValue => MyClass.FromString(colVal))
        .ToList();
int unique = list.Distinct(new MyClassComparer()).Count();

I have a handful of different "profiles" that use the same query but with different types. For example, in addition to MyClass, I have MyOtherClass that also has a FromString method that takes a string parameter, but returns an instance of itself. After I get the list back from the query, I want to call Distinct on it, providing a comparer delegate that is again determined at runtime.

The problem I always run into with this kind of thing is types at build time. I know I can create the comparer like this:

Type comparerType = Type.GetType(String.Format("MyNamespace.{0}Comparer", userProvidedString));
ConstructorInfo ctor = comparerType.GetConstructor(new Type[] { });

But when I call Invoke on the ctor, I still end up with an object that has to be cast. I'm certain this can be done, and that I am simply missing some key concept. Please deliver me an epiphany! Thanks in advance...





Aucun commentaire:

Enregistrer un commentaire