eze*_*981 7 c# lambda expression-trees .net-3.5
我有一个单例,可以注册一个函数来解析每种类型的id值:
public void RegisterType<T>(Func<T, uint> func)
Run Code Online (Sandbox Code Playgroud)
例如:
RegisterType<Post>(p => p.PostId );
RegisterType<Comment>(p => p.CommentId );
Run Code Online (Sandbox Code Playgroud)
然后我想解决一个对象的id,如下所示:
GetObjectId(myPost);
Run Code Online (Sandbox Code Playgroud)
GetObjectId定义的位置
public uint GetObjectId(object obj)
Run Code Online (Sandbox Code Playgroud)
问题是,我如何存储每个func的引用以便最近调用它.问题是每个func都有不同的T类型,我不能做这样的事情:
private Dictionary<Type, Func<object, uint>> _typeMap;
Run Code Online (Sandbox Code Playgroud)
怎么解决呢?表达树?
关于Ezequiel
@SLacks,根据你的建议,我改变了我的方法:
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);
}
Run Code Online (Sandbox Code Playgroud)
谢谢!