Method resolve()
return instance of initialized object from Dictionary, but my question is: is there any way to simplify resolve()
method in a way that we still pass type as argument but after we don't need cast it. I thought about generic resolution but for resolve<ClassAbraKadabra>(typeof(ClassAbraKadabra))
looks repetitive and cant simplified.
class Foo {
//something here
}
//reality
class Resolver{
public void proc() {
Foo foo = (Foo) resolve(typeof(Foo));
}
private object resolve(Type type) {
var obj = getInstanceOfObjectFromMapByType(type):
return obj;
}
}
//expected
class Resolver{
public void proc() {
Foo foo = resolve(typeof(Foo));
}
private ??? resolve(Type type) {
//magic here
}
}
//generic way
class Resolver{
public void proc() {
Foo foo = resolve<Foo>(typeof(Foo));
}
private T resolve<T>(Type type) {
var obj = getInstanceOfObjectFromMapByType(type):
return (T)obj;
}
}
Your generic way was almost there, you don't need to pass in the type just do a typeof(T)
from inside the generic method.
//generic way
class Resolver{
public void proc() {
Foo foo = resolve<Foo>();
}
private T resolve<T>() {
var obj = getInstanceOfObjectFromMapByType(typeof(T)):
return (T)obj;
}
}
If you really must pass in type then the "reality" way is the only option, you have to do the cast at a higher level and just try to return a common interface that is still useful.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.