使用泛型和工作流活动基类编译时出错

时间:2011-05-27 19:32:53

标签: c# generics

任何人都知道为什么这不会编译?问题与继承工作流活动有关。

public class MyActivityBase<T> : System.Workflow.ComponentModel.Activity
{
    public T MyProperty { get; set; }
}

编译错误消息

Error   1   Could not create activity of type '...Activities.Common.MyActivityBase`1'. System.ArgumentException: Cannot create an instance of ...Activities.Common.MyActivityBase`1[T] because Type.**ContainsGenericParameters is true**.
   at System.RuntimeType.CreateInstanceCheckThis()
   at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache)
   at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache)
   at System.Activator.CreateInstance(Type type, Boolean nonPublic)
   at System.Workflow.ComponentModel.Compiler.XomlCompilerHelper.InternalCompileFromDomBatch(String[] files, String[] codeFiles, WorkflowCompilerParameters parameters, WorkflowCompilerResults results, String localAssemblyPath)

谢谢, Ť

1 个答案:

答案 0 :(得分:3)

您的类型正在通过Reflection进行实例化。无论代码是什么,实例化都不知道如何使用Generic参数实例化类型。因此它抛出异常。

不幸的是,如果你想直接使用MyActivityBase<T>,你真的无能为力。您可以通过使用基类的具体子实现(类似public class MyActivityString : MyActivityBase<string>

来实现