如果我正在为通用类编写包装器,我试图将其嵌入到构造中(例如this SO question):
class Foo<T> {
private T value;
private Class<T> type;
public Foo(Class<T> type, T value) {
this.value = value;
this.type = type;
}
public T getValue() {
return value;
}
public Class<T> getType() {
return type;
}
}
我有一个Foo
实例的列表,我希望将其转换成FooWrapper
s的列表,并遵循以下原则:
List<Foo<?>> someListOfFoos = ...
List<FooWrapper<?>> fooWrappers = someListOfFoos
.stream()
.map(foo -> FooWrapper.from(foo))
.collect(Collectors.toList());
构建每个someListOfFoos
时,是否有任何方法可以恢复FooWrapper
中每个元素的类型?遵循以下原则:
class FooWrapper<T> {
private Foo<T> foo;
public static FooWrapper<?> from(Foo<?> toWrap) {
Class<E> type = toWrap.getType(); // i know this is wrong
return new FooWrapper<type>(toWrap); // this is very wrong
}
private FooWrapper(Foo<T> foo) {
this.foo = foo;
}
}
答案 0 :(得分:4)
您只需引入一个通用名称即可对public static List<T> GetAll<T>() where T : class
{
using (var unitOfWork = new UnitOfWork())
{
return unitOfWork.context.Set<T>().ToList();
}
}
public static T GetSingleOrDefault<T>(Expression<Func<T, bool>> predicate) where T : class
{
using (var unitOfWork = new UnitOfWork())
{
return unitOfWork.context.Set<T>().SingleOrDefault(predicate);
}
}
进行一些修改:
FooWrapper#from