如何实现界面? [英] How to realize interface?

查看:64
本文介绍了如何实现界面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好。现在我正在研究接口,不能理解一些接口实现的东西。例如,我有一些代码

 IModelDoc2 swModel;  //   IModelDoc2是一个接口。我们在这里做什么?  
boolstatus = swModel.Extension.SelectByID2(.....); // ..... - 一些参数



我无法理解如何通过从接口调用来实现此方法。类可以实现接口,我们可以从类调用方法。对?但是我们如何从界面实现方法?



请解释。

解决方案

没有。



(正确的术语是实施,而不是实现。)



那里有两种实现接口成员的方法:显式和隐式:

显式: http://msdn.microsoft.com/en-us/library/aa288461%28v=vs.71%29.aspx [ ^ ],

隐式: http://msdn.microsoft.com/en-us/library /aa664590%28v=vs.71%29.aspx [ ^ ]。



显式的明显好处是:如果编译时type (声明类型)的某个变量/ member是实现接口的类,显式实现的成员不能直接调用,你需要这样做的接口引用。但是你不应该强制尝试将类或结构变量强制转换为接口类型。相反,您应该正确使用界面使用的模式。接口是一个功能强大的抽象工具,它允许从知道实现中抽象出一些代码。这意味着这部分代码应该与实现无关,并且永远不会接收实现接口的结构对象的类引用,它应该只接收接口指针:

 < span class =code-keyword> interface  MyInterface {
void MyMethod( / * ... * / );
int MyOtherMethod( / * ... * / );
string MyProperty { get ; set ; }
}

class MyImplementation:MyInterface {
// 显式实现:
void MyInterface.MyMethod( / * ... * / ){ / * ... * / }
string MyInterface.MyProperty { get {返回 / * ... * / ; } set {something = value ; / * ... * / }}
// 甚至隐含:
public int MyOtherMethod( / * ... * / ){ / * ... * / return / * ... * / ; }
// 现在,即使您可能有一些公开(更好的内部)成员,
// 它们不应用于与实现无关的代码
internal void SomeNonInterfaceMethod( / * ... * / ){ / * ... * / }
}

// ...

MyInterface myImplementation = new MyImplementation( / * ... * / );
// NOT MyInterface myImplementation = new MyImplementation(/*...*/) ;

// ...

< span class =code-comment> //
一些与实现无关的方法:
void SomeUsingMethod(MyInterface implementation){ // NOT MyImplementation implementation
// 它会破坏抽象
implementation.MyMethod( / * ... * / );
implementation.MyProperty = some value;
// 但你无法调用
// implementation.SomeNonInterfaceMethod(/*...*/); //将无效
// 如果您需要执行此操作
MyImplementation violatedEncapsulationImplementation =(MyImplementation)实现; // 避免它!
violatedEncapsulationImplementation.SomeNonInterfaceMethod( / * ... * / ); // 避免它!
// 它会起作用,但它表示代码设计错误
}





现在,您知道基本想法。



另见我过去的答案:

当我们使用抽象时,我们使用接口...? [ ^ ],

抽象类和接口之间的区别,如果它们具有相同的no方法和var [ ^ ],

如何决定选择抽象类或接口 [ ^ ],

接口和多态性 [ ^ ]。



请注意最后一个:接口引入了另一种多态,其中使用多态集的代码甚至从元素类型的本质知识中抽象出来:它是引用还是值类型。这是因为像结构这样的值类型可以实现与类相同的接口,这个事实经常被遗忘。



-SA


所有接口都是......最简单的形式......是类的实现。接口提供的一个重要好处(对我而言)是解耦代码......实际上它使你的代码更少依赖于其他类。



示例情况。



假设你有3种不同的货币,美元,印度卢比和欧元。如果没有接口,您将获得此代码。

 UsDollar currency1 =  new  UsDollar(); 



使用各自的课程。如果您想换掉UsDollar作为卢比,您必须更换代码/进行必要的更改以支持下一个班级

卢比货币1 =  new  Rupee(); 



但是通过使用接口,您可以解除依赖关系正在使用的特定类,并使用界面(类似于您发布的示例代码段)。



所以说你有一个实现CurrencyValue整数的接口和一个汇率方法

  public   interface  ICurrency 
{
int CurrencyValue { get ; set ; }
void ExchangeRate( double %);
}



然后,您将拥有从接口继承的以下3个类。请记住,如果某个类继承自该接口,则它们必须实现与接口实现的相同。

  public   class  UsDollar:ICurrency 
{
public int CurrencyValue { get ; set ; }

public void ExchangeRate( double %)
{
Console.WriteLine( 您的汇率Us Dollar是{0},CurrencyValue *%);
}
}

public class 欧元: ICurrency
{
public int CurrencyValue {获得; set ; }

public void ExchangeRate( double %)
{
Console.WriteLine( 您的汇率欧元为{0},CurrencyValue *%);
}
}

public class 卢比: ICurrency
{
public int CurrencyValue {获得; set ; }

public void ExchangeRate( double %)
{
Console.WriteLine( 您的汇率卢比为{0},CurrencyValue *%);
}
}



所以改变你的使用情况来自

卢比货币1 =  new 卢比(); 





 ICurrency currency1 =  new  Rupee(); 



使用此类的代码不再关心它是卢比,美元,欧元......或者你最终创造的任何其他货币类别。



接口也可以提供各种设计模式的价值(因素模式)。



示例用法:



 ICurrency currency1 =  new  UsDollar(); 
ICurrency currency2 = new Euro();
ICurrency currency3 = new Rupee();

currency1.CurrencyValue = 10 ;
currency2.CurrencyValue = 13 ;
currency3.CurrencyValue = 16 ;

currency1.ExchangeRate( 1 1 );
currency2.ExchangeRate( 1 6 );
currency3.ExchangeRate( 1 5 );



所以回答你的问题

 IModelDoc2 swModel;  //   IModelDoc2是一个接口。我们在这里做什么?  



这应该专门创建一个类类型的新对象(在我的例子中,这与ICurrency currency1 = new UsDollar();)相同。因此,在代码中的某个位置,您可以将值分配给swModel,这将是从IModelDoc2继承的某些类/类型。



希望这有助于/澄清一些事情。



但是要阅读接口我会建议以下链接:

http://msdn.microsoft.com/en-us/library/87d83y5b%28v=vs.80%29.aspx [ ^ ]

C#界面(初学者) [ ^ ]

抽象类与界面 [ ^ ]

何时使用接口 [ ^ ]



还有很多其他阅读材料,但这些只是其他一些链接


在两行代码之间的某处,你将有一行实例化一个实现IModelDoc2接口的类的实例。此时,您定义为IModelDoc2类型的变量将由IModelDoc2定义中指定的填充空白的对象表示。


Hello. Now I''am studying interfaces and cann''t understand some things like a interface realizing. For example I have some code

IModelDoc2 swModel; //IModelDoc2 is an interface. What are we doing here? 
boolstatus = swModel.Extension.SelectByID2(.....); //..... - some parameters


I can''t understand how can we realize this method by calling from interface. Class can realize interface and we can call methods from class. Right? But how we realize methods from interface?

Please, explain.

解决方案

No.

(The right term is "to implement", not "to realize".)

There are two ways to implement an interface member: explicit and implicit:
explicit: http://msdn.microsoft.com/en-us/library/aa288461%28v=vs.71%29.aspx[^],
implicit: http://msdn.microsoft.com/en-us/library/aa664590%28v=vs.71%29.aspx[^].

The apparent benefit of explicit is: if the compile-time type (declared type) of some variable/member is the class implementing the interface, explicitly implemented members cannot be called directly, you would need an interface reference to do that. But you should not cast try to cast a class or structure variable to interface type. Instead, you should properly use patterns of the interface use. Interface is a powerful abstraction tool, it allows to abstract some code from knowing the implementation. It means that this part of code should be agnostic to implementation and never receive the class reference of structure objects implementing the interface, it should receive only the interface pointer:

interface MyInterface {
   void MyMethod(/*...*/);
   int MyOtherMethod(/*...*/);
   string MyProperty { get; set; }
}

class MyImplementation : MyInterface {
    // explicit implementations:
    void MyInterface.MyMethod (/*...*/) { /* ... */ }
    string MyInterface.MyProperty { get { return /*...*/; } set { something = value; /*...*/ } }
    // or even implicit:
    public int MyOtherMethod(/*...*/) { /* ... */ return /*...*/; }
    // Now, even you may have some public (better be internal) members,
    // they should not be used in implementation-agnostic code
    internal void SomeNonInterfaceMethod(/*...*/) { /*...*/ }
}

//...

MyInterface myImplementation = new MyImplementation(/*...*/);
// NOT MyInterface myImplementation = new MyImplementation(/*...*/);

//...

//some implementation-agnostic method:
void SomeUsingMethod(MyInterface implementation) { // NOT MyImplementation implementation
                                                   // it would kill the abstraction
    implementation.MyMethod(/*...*/);
    implementation.MyProperty = "some value";
    // but you cannot call
    // implementation.SomeNonInterfaceMethod(/*...*/); // won't work
    // if somewhere you need to do this
    MyImplementation violatedEncapsulationImplementation = (MyImplementation)implementation; // AVOID IT!
    violatedEncapsulationImplementation.SomeNonInterfaceMethod(/*...*/); // AVOID IT!
    // it would work, but it would be an indication of wrong code design
}



Now, you know the basic idea.

See also my past answers:
When we use abstract and when we use interface...?[^],
Difference between abstract class and interface if they have same no of methods and var[^],
How to decide to choose Abstract class or an Interface[^],
Interfaces and Polymorphism[^].

Please pay attention for the last one: interfaces introduce one additional kind of polymorphism, where the code using the polymorphic set is abstracted even from the knowledge of the nature of element type: is it a reference or value type. This is because such value type as structure can implement same interfaces as a class, the fact which is often forgotten.

—SA


All an interface is...in its simplest form...is the implementation for a class. One of the big benefits (to me) that interfaces provide is de-coupling your code...essentially it makes your code less dependent upon other classes.

Example situation.

Say you have 3 different currencies, US Dollar, Indian Rupee, and the Euro. Without an interface you would have this code.

UsDollar currency1 = new UsDollar();


To work with the respective classes. If you wanted to swap out the UsDollar for a Rupee, you''d have to swap out the code/make any changes necessary to support the next class

Rupee currency1 = new Rupee();


But by using an interface, you can de-couple the dependency upon the specific class being used and use the interface instead (similar to how your example snippet you posted).

So Say you have an interface that implements an integer of CurrencyValue and a method of Exchange Rate

public interface ICurrency
{
    int CurrencyValue { get; set; }
    void ExchangeRate(double percent);
}


You would then have the following 3 classes that inherit from the Interface. Remember, if a class inherits from that interface, they must implement the same as what the interface implements.

public class UsDollar : ICurrency
{
    public int CurrencyValue { get; set; }

    public void ExchangeRate(double percent)
    {
        Console.WriteLine("Your Exchange Rate for Us Dollar is {0}", CurrencyValue * percent);
    }
}

public class Euro : ICurrency
{
    public int CurrencyValue { get; set; }

    public void ExchangeRate(double percent)
    {
        Console.WriteLine("Your Exchange Rate for Euro is {0}", CurrencyValue * percent);
    }
}

public class Rupee : ICurrency
{
    public int CurrencyValue { get; set; }

    public void ExchangeRate(double percent)
    {
        Console.WriteLine("Your Exchange Rate for Rupee is {0}", CurrencyValue * percent);
    }
}


So the by changing your usage from

Rupee currency1 = new Rupee();


To

ICurrency currency1 = new Rupee();


Your code that is using this class no longer cares if it is a Rupee, Us Dollar, Euro...or whatever other currency classes you end up creating.

Interfaces can also provide value in various design patterns as well (factor pattern).

Example Usage:

ICurrency currency1 = new UsDollar();
ICurrency currency2 = new Euro();
ICurrency currency3 = new Rupee();

currency1.CurrencyValue = 10;
currency2.CurrencyValue = 13;
currency3.CurrencyValue = 16;

currency1.ExchangeRate(1.1);
currency2.ExchangeRate(1.6);
currency3.ExchangeRate(1.5);


So to answer your question

IModelDoc2 swModel; //IModelDoc2 is an interface. What are we doing here? 


This should specifically be creating a new object of some class type (in my example this would be same as ICurrency currency1 = new UsDollar();). So somewhere in your code you would be assigning the value to swModel which would be some class/type that inherits from IModelDoc2.

Hope this helps/clarifies things for you.

But to read up on interfaces i would suggest following links:
http://msdn.microsoft.com/en-us/library/87d83y5b%28v=vs.80%29.aspx[^]
Interfaces in C# (For Beginners)[^]
Abstract Class versus Interface[^]
When To Use Interfaces[^]

There is plenty of other reading, but those are just a few other links


Somewhere between your two lines of code, you''re going to have a line that instantiates an instance of a class that implements the interface IModelDoc2. At that point, the variable you defined as being of type IModelDoc2 will be represented by an object that "fills in the blanks" specified in IModelDoc2''s definition.


这篇关于如何实现界面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆