码迷,mamicode.com
首页 > 其他好文 > 详细

Automatic Code Generation-->Implement Interface

时间:2015-07-16 16:27:13      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

https://msdn.microsoft.com/en-us/library/hk90416s(v=vs.110).aspx

VS中自带的只能提示,一个类继承自某一个接口。

由VS为类生成接口所要求的方法

using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;

namespace BusinessServiceContracts
{
    [ServiceContract(Namespace = "http://www.thatindigogirl.com/samples/2006/06")]
    public interface IServiceA
    {
        [OperationContract]
        string Operation1();
        [OperationContract]
        string Operation2();
    }
}

 

 

public class ServiceA : IServiceA, IAdmin
{

}

现有代码如上

把鼠标的光标点在IServiceA的第一个字母I前面

技术分享

这个时候会发现I字母线面有一个蓝色的下划线

 

让鼠标悬停在蓝色的下划线上,会出现一个小图标,单击一下

技术分享

 

技术分享

 

根据需要选择其中一个,来自动生成代码

实现接口IServiceA

using System;
using System.Collections.Generic;
using System.Text;
using BusinessServiceContracts;

namespace BusinessServices
{
    public class ServiceA : IServiceA, IAdmin
    {

        public string Operation1()
        {
            throw new NotImplementedException();
        }

        public string Operation2()
        {
            throw new NotImplementedException();
        }
    }
    
}

 

显示实现接口IServiceA

using System;
using System.Collections.Generic;
using System.Text;
using BusinessServiceContracts;

namespace BusinessServices
{
    public class ServiceA : IServiceA, IAdmin
    {

        string IServiceA.Operation1()
        {
            throw new NotImplementedException();
        }

        string IServiceA.Operation2()
        {
            throw new NotImplementedException();
        }
    }
    
}

 

第一种,实现接口,是public 方法

第二种,显示实现接口,方法直接完全限定了

 

显示接口和隐式接口的区别:

隐式实现的话实现的方法属于实现的类的,可以直接通过类的对象访问,
显式实现的话方法是属于接口的,可以看成是寄托在类中实现的,访问这些方法时要先把对象转换成接口对象,然后通过接口对象调用,

    interface ICalculate
    {
        void Add();
        void Substract();
    }
    class Math : ICalculate
    {
        void ICalculate.Add()
        {
            throw new NotImplementedException();
        }

        void ICalculate.Substract()
        {
            throw new NotImplementedException();
        }
    }

调用方式

Math类型的实例是无法访问Add方法的

只有接口类型的实例,才可以访问Add方法。  即,需要把Math类型的实例先转换ICalculate才会用到

    Math math = new Math();
            ICalculate iMath = new Math();
            iMath.Add();

 

Automatic Code Generation-->Implement Interface

标签:

原文地址:http://www.cnblogs.com/chucklu/p/4651328.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!