Is it possible to achieve having typed func
in a dict, with different types as keys and no casting in the func
.
Something like this:
class Program
{
class Person
{
public int Id { get; set; }
}
class Dog
{
public string Name { get; set; }
}
static void Main(string[] args)
{
var funcDict = new Dictionary<Type, Func<object, object, bool>>()
{
{typeof(Person), (Person p1, Person p2) => p1.Id == p2.Id},
{typeof(Dog), (Dog d1, Dog d2) => d1.Name == d2.Name},
};
var p1 = new Person()
{
Id = 4
};
var p2 = new Person();
Console.WriteLine(funcDict[p1.GetType()].Invoke(p1, p2));
}
}
Best I can come up with is creating the funcs with object
types and then casting in the func
body, but if possible would like to avoid that, cause it would make for a much cleaner API.
var funcDict = new Dictionary<Type, Func<object, object, bool>>()
{
{typeof(Person), (o1, o2) => ((Person) o1).Id == ((Person) o2).Id},
};
Aucun commentaire:
Enregistrer un commentaire