Search code examples
c#.net-3.5lambdaexpression-trees

references to Func's of different types


I have a singleton that can register a func to resolve an id value for each type:

public void RegisterType<T>(Func<T, uint> func)

for example:

RegisterType<Post>(p => p.PostId );
RegisterType<Comment>(p => p.CommentId );

and then i want to resolve the id for an object, like these:

GetObjectId(myPost);

where GetObjectId definition is

public uint GetObjectId(object obj)

The question is, how can i store a reference for each func to invoke it lately. The problem is that each func has a different T type, and I can't do something like this:

private Dictionary<Type, Func<object, uint>> _typeMap;

How can resolve it? Expression trees?

regards Ezequiel


Solution

  • @SLacks, following your advise i have changed my approach to:

    private Dictionary<Type, Func<object, uint>> _typeMap;
    
    public void RegisterType<T>(uint typeId, Func<T, uint> func)
    {            
        _typeMap[typeof(T)] = (o) => func((T)o);
    }
    
    public uint GetObjectId(object obj)
    {
        return _typeMap[obj.GetType()](obj);
    }
    

    thanks!