我已经花了几个小时来解决一个问题,我认为我离成功不远了。我正在开发一个应用程序,我们可能会有50-100种类型的应用程序都是以相同的方式运行的。因此,我尝试将其设计成通用的,而不是创建50-100个类。以下是我的代码:
这是基本类:
public class RavenWriterBase<T> : IRavenWriter<T> where T : class, IDataEntity
这是界面:
public interface IRavenWriter<T>
{
int ExecutionIntervalInSeconds { get; }
void Execute(object stateInfo);
void Initialize(int executionIntervalInSeconds, Expression<Func<T, DateTime>> timeOrderByFunc);
}
这是我如何使用它的方法:
private static void StartWriters()
{
Assembly assembly = typeof(IDataEntity).Assembly;
List<IDataEntity> dataEntities = ReflectionUtility.GetObjectsForAnInterface<IDataEntity>(assembly);
foreach (IDataEntity dataEntity in dataEntities)
{
Type dataEntityType = dataEntity.GetType();
Type ravenWriterType = typeof(RavenWriterBase<>).MakeGenericType(dataEntityType);
Expression<Func<IDataEntity, DateTime>> func = x => x.CicReadTime;
// This is where I'm stuck. How do I activate this as RavenWriterBase<T>?
var ravenWriter = Activator.CreateInstance(ravenWriterType);
//ravenWriter.Initialize(60, func); // I can't do this until I cast.
// More functionality here (not part of this issue)
}
}
我卡在上面这行代码无法继续了:
var ravenWriter = Activator.CreateInstance(ravenWriterType);
这是我的问题:
我该如何将其用作RavenWriterBase或IRavenWriter?类似于以下内容:
ravenWriter.Initialize(60, func);
我认为需要像这样的东西,但我需要为IRavenWriter<>指定一个类型,而我还不知道它是什么:
var ravenWriter = Activator.CreateInstance(ravenWriterType) as IRavenWriter<>;
如果我将鼠标悬停在ravenWriter上,我的对象就会成功出现:
但是现在我需要以一种通用的方式来使用它。我该如何做?
更新:
我想到了使用动态关键字,这个方法可行:
dynamic ravenWriter = Activator.CreateInstance(ravenWriterType);
ravenWriter.Initialize(60);
我有点作弊,因为我意识到每个IDataEntity的Func是相同的,所以不需要将其作为参数传递给Initialize()。然而,至少现在我可以调用Initialize()了。但既然Func是相同的,我也不应该需要泛型接口。