我已经花了几个小时研究一个问题了,我想我已经很接近了。我正在开发一个应用程序,我们可以有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);

这是我的问题:
我怎么能把它当作乌鸦城或伊朗作家?类似于:
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是相同的,我也不需要通用接口。

最佳答案

我的解决办法是:
创建IRavenWriter的非通用接口
使IRavenWriter<T>IRavenWriter继承
保持ExecuteExecutionIntervalInSecondsIRavenWriter
使IRavenWriter具有Func<DateTime>并在您的作者中使用它
Initialize移动到IRavenWriter<T>
使用工厂根据类型和表达式初始化func:
例如:

public class MyDateTime
{
    public DateTime This { get; set; }
}

public static Func<DateTime> GetFunk<T>(Expression<Func<T, DateTime>> timeOrderByFunc, T t)
{
    return () => timeOrderByFunc.Compile()(t);
}

你使用:
GetFunk<MyDateTime>(x => x.This, new MyDateTime(){This = DateTime.Now});

08-17 15:54