5

我正在用 C# 构建一个 WCF,以及一个同时使用它的客户端。出于某种原因,我无法获得返回 int 的方法。这是我的合同:

[ServiceContract]
public interface IMData
{
  [OperationContract]
  int ReturnAnInt();

  [OperationContract]
  String HelloWorld();
}

这是我实现它的地方:

public class MData : IMData
{
  public String HelloWorld()
  {
    return "Hello World";
  }

  public int ReturnAnInt()
  {
    return 5;
  }
}

我正在使用 Visual Studio,对于客户端,我将此 WCF 作为 Web 引用导入。现在由于某种原因,当我声明一个 MData 实例并尝试调用 HelloWorld 时,没有问题,但是在调用 ReturnAnInt 时出现编译错误。

MData m = new MData();
String helloWorld = m.HelloWorld();
int result = m.ReturnAnInt();

ReturnAnInt 得到的错误是:“方法 'ReturnAnInt' 没有重载需要 0 个参数”然后我将鼠标悬停在 Visual Studio 的预期上,它说该方法应该如下所示:

void MData.ReturnAnInt(out int ReturnAnIntResult, out bool ReturnAnIntResultSpecified)

几个小时以来,我一直在用头撞墙,在谷歌上找不到任何东西,这也让我的同事感到困惑。为什么要添加两个定义中没有的 out 参数,并更改返回类型?任何帮助将不胜感激。如果我遗漏了任何有用的信息,我深表歉意。

4

3 回答 3

4

您可以将其作为服务参考(新技术)而不是 Web 参考(旧技术)导入吗?我通过服务引用使用 WCF 服务并且没有看到这样的问题 -当服务定义不允许指定时(SpecifiedWCF-根据我的经验,生成的服务定义按预期工作)。intoutint

如果您找不到更好的解决方案,这里有一个使用部分类的解决方法:(这必须在您返回 a 时完成struct,而不仅仅是ints)

public partial class MData
{
    public int ReturnAnInt()
    {
        int result;
        bool specified;
        this.ReturnAnInt(out result, out specified);
        if (!specified) throw new InvalidOperationException();
        return result;
    }
}

更新 http://www.codeproject.com/Articles/323097/WCF-ASMX-Interoperability-Removing-the-Annoying-xx有一个(有点笨拙)的解决方案,并告诉我们根本原因是 WCF 生成不良(可以说不准确的)WSDL - 他们有一个minOccurs="0"真正不需要的元素。Web References 按原样读取此内容,并生成笨拙的代码来处理它,这就是您要处理的内容。根据他的文章,您可以返回此类型而不是int

[MessageContract(IsWrapped = false)]
public class MyInt
{
    [MessageBodyMember]
    public int Result { get; set; }

    public static implicit operator MyInt(int i)
    {
        return new MyInt { Result = i };
    }

    public static implicit operator int(MyInt m)
    {
        return m.Result;
    }
}

除了修改方法的返回类型:

[ServiceContract]
public interface IMData
{
    [OperationContract]
    MyInt ReturnAnInt();

    [OperationContract]
    String HelloWorld();
}
public class Service1 : IMData
{
    public MyInt ReturnAnInt()
    {
        return 4;
    }

    public string HelloWorld()
    {
        return "Hello World";
    }
}
于 2012-10-18T22:38:59.050 回答
2

您将其作为服务参考(带有名称空间MData)而不是 Web 参考导入。

并使用下面的代码,

MDataClient m = new MDataClient(); 
String helloWorld = m.HelloWorld(); 
int result = m.ReturnAnInt();

您的代码没有任何问题。如果您添加服务参考并使用上述代码段,它应该可以正常工作。

于 2012-10-19T01:53:09.043 回答
0

我有一个类似的问题,我无法让out int我的 Web 服务的参数工作。由于这到底是什么,我仍然不确定,但我使用stringasout参数让它工作。

[OperationContract]
LoginStatus GetLogin(string username, string password, out string s_uId);

在网络服务方面:

s_uId = uId.ToString();

在客户端:

int uId;
string s_uId;
result = client.GetLogin(username, password, out s_uId);
Int32.TryParse(s_uId, out uId);
于 2017-11-08T13:46:50.513 回答