WCF

1.

2.创建和使用

(1)创建
1.

2.

3.

实现类部分代码:

public class MyWCF : IMyWCF
{
    public void DoWork()
    {
        Console.WriteLine("1213456");
    }

    public string GetString()
    {
        return "1213456";
    }

    public List<WebServiceUser> GetUserList(int index)
    {
        return new List<WebServiceUser>()
            {
                new WebServiceUser()
                {
                    Id=123,
                    Age=23,
                    Sex=0,
                    Name="MrSorry",
                    Description="高级班的学员1"
                },
                new WebServiceUser()
                {
                    Id=234,
                    Age=34,
                    Sex=0,
                    Name="专注",
                    Description="高级班的学员2"
                },
            };
    }

    public void HelloWord()
    {
        Console.WriteLine("1213456");
    }
}

以上就是创建了一个简单的WCF服务

(2)使用
用的是测试类

/// <summary>
/// 单元测试
/// </summary>
[TestClass]
public class WCFTest
{
    [TestMethod]
    public void TestMethod1()
    {
        //一般不用这种写法
        //using (MyWebWCF.MyWCFClient client = new MyWebWCF.MyWCFClient())
        //{
        //    client.DoWork();
        //    string result = client.GetString();
        //    var list = client.GetUserList(1);
        //}

        //这是标准写法
        MyWebWCF.MyWCFClient client = null;
        try
        {
            client = new MyWebWCF.MyWCFClient();
            client.DoWork();
            string result = client.GetString();
            var list = client.GetUserList(1);
            client.Close();//在关闭时可能出异常
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            if (client != null)
                client.Abort();
            throw;
        }

    }
}
posted @ 2020-04-15 21:26  WEasiness  阅读(126)  评论(0)    收藏  举报