Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 296
eze1981 Avatar asked Feb 28 '11 14:02

eze1981


People also ask

What are the reference types in Swift?

Types in Swift fall into one of two categories: first, “value types”, where each instance keeps a unique copy of its data, usually defined as a struct, enum, or tuple. The second, “reference types”, where instances share a single copy of the data, and the type is usually defined as a class.

How many reference types are there?

In Java there are four types of references differentiated on the way by which they are garbage collected. Strong References: This is the default type/class of Reference Object. Any object which has an active strong reference are not eligible for garbage collection.

What is meant by reference type and value type?

Variables of reference types store references to their data (objects), while variables of value types directly contain their data. With reference types, two variables can reference the same object; therefore, operations on one variable can affect the object referenced by the other variable.

Why are closures reference types?

Closures Are Reference TypesWhenever you assign a function or a closure to a constant or a variable, you are actually setting that constant or variable to be a reference to the function or closure.


1 Answers

You don't need Expression Trees to do it the way you are suggesting, just need to nest the function when registering it.

public void RegisterType<T>(Func<T, uint> func){
             _typeMap.Add(typeof(T), obj=>func((T)obj));
}
like image 173
jbtule Avatar answered Oct 18 '22 22:10

jbtule