";检测到不可达代码”;在WCF服务中时

本文关键字:WCF 代码 服务 检测 quot | 更新日期: 2023-09-27 18:28:00

这个问题与这个问题直接相关,但我想因为主题不同,我会为当前问题开始一个新问题。我有一个WCF服务、一个服务和一个GUI。GUI将一个int传递给WCF,WCF应该将其放入List<int> IntList;那么在该服务中,我想访问该列表。问题是,当我尝试添加到WCF服务中的列表时,我收到了"检测到不可访问的代码"警告,并且在调试时完全跳过了添加行。如何使此列表"可访问"?

以下是WCF代码、对WCF的GUI调用以及使用WCF:中的List<>的服务

WCF:

[ServiceContract(Namespace = "http://CalcRAService")]
public interface ICalculator
{
    [OperationContract]
    int Add(int n1, int n2);
    [OperationContract]
    List<int> GetAllNumbers();
}
// Implement the ICalculator service contract in a service class.
public class CalculatorService : ICalculator
{
    public List<int> m_myValues = new List<int>();
    // Implement the ICalculator methods.
    public int Add(int n1,int n2)
    {
        int result = n1 + n2;
        return result;
        m_myValues.Add(result);
    }
    public List<int> GetAllNumbers()
    {
        return m_myValues;
    }
}

GUI:

private void button1_Click(object sender, EventArgs e)
        {
            using (ChannelFactory<ICalculator> factory = new ChannelFactory<ICalculator>(new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/MyServiceAddress")))
            {
                ICalculator proxy = factory.CreateChannel();                
                int trouble = proxy.Add((int)NUD.Value,(int)NUD.Value);
            }
        }

服务:

protected override void OnStart(string[] args)
{
    if (mHost != null)
    {
        mHost.Close();
    }
    mHost = new ServiceHost(typeof(CalculatorService), new Uri("net.pipe://localhost"));
    mHost.AddServiceEndpoint(typeof(ICalculator), new NetNamedPipeBinding(), "MyServiceAddress");
    mHost.Open();
    using (ChannelFactory<ICalculator> factory = new ChannelFactory<ICalculator>(new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/MyServiceAddress")))
    {
        ICalculator proxy = factory.CreateChannel();
        BigList.AddRange(proxy.GetAllNumbers());
    }
}

";检测到不可达代码”;在WCF服务中时

所以你有:

int result = n1 + n2;
return result; // <-- Return statement
m_myValues.Add(result); // <-- This code can never be reached!

既然m_myValues.Add()不会以任何方式改变result的状态,为什么不翻转这些行呢:

int result = n1 + n2;
m_myValues.Add(result);
return result;