【问题标题】:Workflow Foundation - Activity: Is it possible to cast a OutArgument?工作流基础 - 活动:是否可以投射 OutArgument?
【发布时间】:2019-11-26 13:11:30
【问题描述】:

我对活动的 OutArgument 有疑问。这是一个简化的代码示例:

    public class Animal
    {
    }

    public class Dog : Animal
    {
    }

    public class CreateNewDogActivity : CodeActivity<Dog>
    {
        protected override Dog Execute( CodeActivityContext context )
        {
            return new Dog();
        }
    }

    public class Program
    {
        public void Start()
        {
            Variable<Animal> animal = new Variable<Animal>( "animal" );

            var createDogStep = new FlowStep
            {
                Action = new CreateNewDogActivity()
                {
                    Result = new OutArgument<Dog>( animal )
                }
            };

            var flowChart = new Flowchart()
            {
                Variables = { animal },
                StartNode = createDogStep,
                Nodes = {
                    createDogStep
                }
            };

            WorkflowInvoker.Invoke( flowChart );
        }
    }

在运行时出现以下错误:

测试方法 UnitTests.Base.Mvc.Workflow.OutArgumentTest.OutArgumentProgramTest 抛出异常: System.Activities.InvalidWorkflowException:处理工作流树时遇到以下错误: “VariableReference”:变量“System.Activities.Variable`1[UnitTests.Base.Mvc.Workflow.Animal]”不能用于“UnitTests.Base.Mvc.Workflow.Dog”类型的表达式,因为它属于类型'UnitTests.Base.Mvc.Workflow.Animal' 不兼容。

将“狗”类型的 Result-OutArgument 分配给“动物”类型的变量的最简单方法是什么?

谢谢!

【问题讨论】:

  • 新的(动物)(OutArgument(动物)
  • 能否提供更多关于 OutArgument 的背景信息?构造函数签名是什么?
  • @PaulTsai OutArgument 是 Workflow Foundation 的一部分 OutArgument<T> Class

标签: c# workflow workflow-foundation workflow-activity


【解决方案1】:

当变量Animal被声明时,它的类型被设置为Animal类型的变量。但是,当您声明 Dog 类型的 OutArgument 时,您将一个动物传递给它。这失败了,因为动物变量与狗变量不兼容,并且泛型确保了类型安全。如需进一步阅读,请查看covariance and contravariance

解决方法如下。

FlowStep createDogStep;
var doggy = animal as Variable<Dog>;
if (doggy != null) {
    createDogStep = new FlowStep {
        Action = new CreateNewDogActivity()
        {
            Result = new OutArgument<Dog>( doggy )
        }
};

【讨论】: