【问题标题】:C# WinForms Try Catch Inside a classC# WinForms 尝试在类中捕获
【发布时间】:2014-03-08 11:28:24
【问题描述】:

我正在使用连接到 Internet 的服务参考,如果连接失败,我想在消息框中显示消息。如何在具有 void 返回类型的类的成员函数中调用消息框?这是类的成员函数:

 public void ReverseGeocodePoint()
    {
        try{
        string results = "";
        string key = "abc";
        ReverseGeocodeRequest reverseGeocodeRequest = new ReverseGeocodeRequest();

        // Set the credentials using a valid Bing Maps key
        reverseGeocodeRequest.Credentials = new GeocodeService.Credentials();
        reverseGeocodeRequest.Credentials.ApplicationId = key;

        // Set the point to use to find a matching address
        GeocodeService.Location point = new GeocodeService.Location();
        point.Latitude = latitude;
        point.Longitude = longitude;

        reverseGeocodeRequest.Location = point;

        // Make the reverse geocode request
        GeocodeServiceClient geocodeService = new GeocodeServiceClient("BasicHttpBinding_IGeocodeService");
        //This will connect to the server
        GeocodeResponse geocodeResponse = geocodeService.ReverseGeocode(reverseGeocodeRequest);

        if (geocodeResponse.Results.Length > 0)
            results = geocodeResponse.Results[0].DisplayName;
        else
            results = "No Results found";

        address = results;
    }} catch{ //here I want to show a msgbox but the problem is, this is not the form class}

【问题讨论】:

  • 发布代码有助于更好地理解您的问题。
  • 您需要向我们展示您的代码。你拥有的东西和你试图写的东西都不起作用。

标签: c# winforms exception exception-handling


【解决方案1】:

如果您对此无能为力,请不要在该类中捕获异常。让它冒泡并抓住它可以对它做点什么:

public class MyForm : Form
{
    public void SomeMethod()
    {
        try
        {
            var sc = new ServiceClass();
            sc.ReverseGeocodePoint();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}

ReverseGeocodePoint() 中,删除try/catch 语句。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-05
    • 1970-01-01
    • 2011-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-30
    相关资源
    最近更新 更多