【发布时间】:2019-11-10 01:01:04
【问题描述】:
我在 C# 中创建了一个用于 Q# 程序的库。该库有两个脚本,一个名为“Class1.cs”的 C# 类库和一个名为“Util.qs”的匹配 Q# 脚本,我在这里分享每个的代码 sn-p:
Class1.cs:
using System;
using Microsoft.Quantum.Simulation.Common;
using Microsoft.Quantum.Simulation.Core;
using Microsoft.Quantum.Simulation.Simulators;
namespace MyLibrary {
class Class1 : QuantumSimulator {
static void Method_1 (string str) { ... }
.
.
.
}
}
Util.qs:
namespace MyLibrary {
operation Op_1 (str : String) : Unit { body intrinsic; }
}
在不同的命名空间中有另一个 Q# 程序使用命名空间“MyLibrary”,所以在添加引用后,在这个 Q# 程序中我有:
namespace QSharp
{
open Microsoft.Quantum.Canon;
open Microsoft.Quantum.Intrinsic;
open MyLibrary;
operation TestMyLibrary() : Unit {
Op_1("some string");
}
}
当我在终端中执行“dotnet run”时,我会收到以下消息:
Unhandled Exception: System.AggregateException: One or more errors
occurred. (Cannot create an instance of MyLibrary.Op_1 because it is
an abstract class.) ---> System.MemberAccessException: Cannot create
an instance of MyLibrary.Op_1 because it is an abstract class.
我该如何解决?
谢谢。
更新:
按照 Mariia 的回答并检查 Quantum.Kata.Utils,我将代码更改如下:
所以,我将 Class1 脚本更改为:
using System;
using Microsoft.Quantum.Simulation.Common;
using Microsoft.Quantum.Simulation.Core;
using Microsoft.Quantum.Simulation.Simulators;
namespace MyLibrary {
class Class1 : QuantumSimulator {
private string classString = "";
public Class1() { }
public class Op_1_Impl : Op_1{
string cl_1;
public Op_1_Impl (Class1 c) : base (c) {
cl_1 = c.classString;
}
public override Func<string, QVoid> Body => (__in) => {
return cl1;
};
}
}
现在错误消息是:
error CS0029: Cannot implicitly convert type 'string' to 'Microsoft.Quantum.Simulation.Core.QVoid'
error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types
in the block are not implicitly convertible to the delegate return type
检查 Quantum.Kata.Utils 后,我意识到我需要为作为基类的 Class1 创建一个字段和一个构造函数,并且我应该覆盖 Func<string, QVoid>,因为 Op_1 参数是字符串类型。但我不确定这些步骤中的每一个是否单独完成?
第二次更新:
我在第一次更新时将之前的 c# 代码更改为以下代码:
using System;
using Microsoft.Quantum.Simulation.Common;
using Microsoft.Quantum.Simulation.Core;
using Microsoft.Quantum.Simulation.Simulators;
namespace MyLibrary {
class Class1 : QuantumSimulator {
public Class1() { }
public class Op_1_Impl : Op_1{
Class1 cl_1;
public Op_1_Impl (Class1 c) : base (c) {
cl_1 = c;
}
public override Func<string, QVoid> Body => (__in) => {
return QVoid.Instance;
};
}
}
现在错误信息与第一条相同:
Unhandled Exception: System.AggregateException: One or more errors
occurred. (Cannot create an instance of MyLibrary.Op_1 because it is
an abstract class.) ---> System.MemberAccessException: Cannot create
an instance of MyLibrary.Op_1 because it is an abstract class.
在这个新代码中,构造函数public Class1() { } 不应该有参数吗?如果是,是什么数据类型?
【问题讨论】:
标签: q#