C# 使用与多重继承相关的接口的任何真实示例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1929884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 21:57:11  来源:igfitidea点击:

Any real example of using interface related to multiple inheritance

c#asp.netvb.netinterfacemultiple-inheritance

提问by Shantanu Gupta

I m trying to understand Interfaces so that I can implement them in my programs but I m not able to imagine how should i use them. Also give me some eg of using them with multiple inheritance in C#

我试图理解接口,以便我可以在我的程序中实现它们,但我无法想象我应该如何使用它们。还给我一些在 C# 中使用多重继承的例子

采纳答案by Matthew Groves

A good example for an interface is a repository pattern. Your interface will define methods like Get, GetAll, Update, Delete, etc. No implementation, just function signatures.

接口的一个很好的例子是存储库模式。您的接口将定义 Get、GetAll、Update、Delete 等方法。没有实现,只有函数签名。

Then, you can write a 'concrete' implementation of that class to work with, say, MySQL. Your UI should only refer to the interface, though.

然后,您可以编写该类的“具体”实现以与 MySQL 等一起工作。不过,您的 UI 应该只引用界面。

Later, if you decide to change to Microsoft SQL, you write another concrete implementation, but your UI code doesn't have to change (much).

稍后,如果您决定更改为 Microsoft SQL,您将编写另一个具体实现,但您的 UI 代码不必更改(太多)。

Multiple inheritance doesn't exist in C#, in the sense that you can only inherit from one 'concrete' class; though you can inherit (or 'implement') as many interfaces as you want.

C# 中不存在多重继承,因为您只能从一个“具体”类继承;尽管您可以根据需要继承(或“实现”)任意数量的接口。

回答by Brett Veenstra

Interfaces simply define a contractof the public elements (e.g. properties, methods, events) for your object, not behavior.

接口只是为您的对象定义公共元素(例如属性、方法、事件)的契约,而不是行为。

interface IDog
{
    void WagTail();    //notice no implementation
    ISound Speak();    //notice no implementation
}

class Spaniel : IDog
{
    public void WagTail()
    {
        Console.WriteLine("Shook my long, hairy tail");
    }

    public ISound Speak()
    {
        return new BarkSound("yip");
    }

}

class Terrier : IDog
{
    public void WagTail()
    {
        Console.WriteLine("Shook my short tail");
    }

    public ISound Speak()
    {
        return new BarkSound("woof");
    }
}

UPDATE

更新

In "real examples" I use interfaces with: - Unit Testing - GENERICS (e.g. Repository, Gateway, Settings)

在“真实示例”中,我使用以下接口: - 单元测试 - GENERICS(例如存储库、网关、设置)

interface Repository<T>{
    T Find(Predicate<T>);
    List<T> ListAll();
}

interface Gateway<T>{
    T GetFrom(IQuery query);
    void AddToDatabase(IEntity entityItem);
}

interface Settings<T>{
    string Name { get; set; }
    T Value { get; set; }
    T Default { get; }
}

回答by dsimcha

Sometimes being too abstract just gets in the way and referring to implementation details actually clarifies things. Therefore, I'll provide the close to the metal explanation of interfaces that made me finally grok them.

有时过于抽象只会碍手碍脚,参考实现细节实际上可以澄清事情。因此,我将提供接近于金属的接口解释,使我最终理解它们。

An interface is just a way of declaring that a class implements some virtual functions and how these virtual functions should be laid out in the class's vtable. When you declare an interface, you're essentially giving a high-level description of a virtual function table to the compiler. When you implement an interface, you're telling the compiler that you want to include the vtable referred to by that interface in your class.

接口只是声明一个类实现了一些虚函数以及这些虚函数应该如何在类的vtable 中布局的一种方式。当您声明一个接口时,您实际上是在向编译器提供虚函数表的高级描述。当你实现一个接口时,你告诉编译器你想在你的类中包含该接口引用的 vtable。

The purpose of interfaces is that you can implicitly cast a class that implements interface I to an instance of interface I:

接口的目的是您可以将实现接口 I 的类隐式转换为接口 I 的实例:

interface I {
    void doStuff();
}

class Foo : I {
    void doStuff() {}

    void useAnI(I i) {}
}

var foo = new Foo();
I i = foo;  // i is now a reference to the vtable pointer for I in foo.
foo.useAnI(i);  // Works.  You've passed useAnI a Foo, which can be used as an I.

回答by Vladimir

Here is one (in Java, but this is not important since they're similiar): In my project I've created simple interface:

这是一个(在 Java 中,但这并不重要,因为它们很相似):在我的项目中,我创建了简单的界面:

public interface Identifiable<T> {
    public T getId();
}

Which is simple replacement to some sorts of annotations. The next step: I've made all entity classes implement this interface.

这是对某种注释的简单替换。下一步:我已经让所有实体类都实现了这个接口。

The third step is to write some syntax-sugar-like methods:

第三步是写一些语法糖类的方法:

public <T> List<T> ids(List<? extends Identifiable<T> entities) { ... }

This was just an example.

这只是一个例子。

The more complex example is something like validation rules: you have some validation engine (probably written by you) and a simple interface for rule:

更复杂的示例类似于验证规则:您有一些验证引擎(可能由您编写)和一个简单的规则接口:

public interface ValidationRule {
    public boolean isValid(...);
}

So, this engine requires the rules to be implemented by you. And of course there will be multiple inheritance since you'll certainly wish more then a single rule.

所以,这个引擎需要你来实现规则。当然,会有多重继承,因为您肯定希望不止一个规则。

回答by DanDan

Take a look at something you are familiar with - ie a List collection in C#. Lists define the IList interface, and generic lists define the IList interface. IList exposes functions such as Add, Remove, and the List implements these functions. There are also BindingLists which implement IList in a slightly different way.

看一看您熟悉的东西 - 即 C# 中的 List 集合。列表定义了 IList 接口,通用列表定义了 IList 接口。IList 暴露了 Add、Remove 等函数,List 实现了这些函数。还有 BindingLists 以稍微不同的方式实现 IList。

I would also recommend Head First Design Patterns. The code examples are in Java but are easily translated into C#, plus they will introduce you to the real power of interfaces and design patterns.

我还推荐Head First Design Patterns。代码示例是用 Java 编写的,但很容易翻译成 C#,此外,它们还将向您介绍接口和设计模式的真正威力。

回答by Eric

I am writing a video game. In this video game I apply different forces to objects in the game. Thrust forces, impact forces, gravitational forces. While they are calculated differently, they all have the same basic elements. I need to call an update function that will evaluate the force and add the force to the object it's attached to.

我正在写一个视频游戏。在这个视频游戏中,我对游戏中的物体施加了不同的力。推力、冲击力、重力。虽然它们的计算方式不同,但它们都具有相同的基本要素。我需要调用一个更新函数来评估力并将力添加到它所连接的对象上。

So, what I've done is create an IForce interface that has an update function for its signature. All of my forces implement this interface:

所以,我所做的是创建一个 IForce 接口,该接口具有更新功能的签名。我所有的力量都实现了这个接口:

public interface IForce
{
    void Update(Particle particle, GameTime gameTime);
}

Here is a sample implementation.

这是一个示例实现。

public class Spring : IForce
{
    private Particle ThisParticle;
    private Particle ThatParticle;

    private float K;

    public Spring(Particle thisParticle, Particle thatParticle, float k)
    {
        ThisParticle = thisParticle;
        ThatParticle = thatParticle;
    }

    public void Update(Particle particle, GameTime gameTime)
    {            
        float X = Vector3.Length(ThisParticle - ThatParticle);

        ThisParticle.Forces.Add(K * X);
    }
}

The update function has a simplified spring force update to make it easier to understand.

更新功能有一个简化的弹簧力更新,使其更容易理解。

This helps in a few ways.

这在几个方面有帮助。

I can completely change the way a force is calculated without effecting other parts of my code. I do this all the time. Along the same lines, it is rediculously easy for me to add new forces. As long as it implements the IForce interface I know it will mesh well with my existing code.

我可以完全改变力的计算方式,而不会影响我代码的其他部分。我一直这样做。同样,我很容易添加新的力量。只要它实现了 IForce 接口,我就知道它会与我现有的代码很好地融合。

Another way it helps is with handling a large number of forces. I have a force registry that has a List of IForce. Since all forces implement that interface and have an Update function it's very easy to update all the forces in my game. When I create the force I add it to the list. Then, I loop through the list and call each elements update function without worrying about what type of force it is and all my forces update.

它的另一种帮助方式是处理大量力。我有一个包含 IForce 列表的强制注册表。由于所有力都实现了该接口并具有更新功能,因此很容易更新我游戏中的所有力。当我创建力时,我将其添加到列表中。然后,我遍历列表并调用每个元素更新函数,而不必担心它是什么类型的力以及我所有的力都会更新。

I use interfaces every day in a lot of different situations. They are fantastic!

我每天都在许多不同的情况下使用界面。他们太棒了!

回答by Fozi

Multiple inheritance is about having a class be usable in multiple situations: [pseudo code]

多重继承是关于让一个类在多种情况下可用:[伪代码]

interface Shape {
    // shape methods like draw, move, getboundingrect, whatever.
}

interface Serializable {
    // methods like read and write
}

class Circle : public Shape, public Serializable {
    // TODO: implement Shape methods
    // TODO: implement Serializable methods
}

// somewhere later
{
    Circle circle;
    // ...
    deserializer.deserialize(circle);
    // ...
    graphicsurface.draw(circle);
    // ...
    serializer.serialize(circle);
}

The idea is that your Circle class implements two different interfaces that are used in very different situations.

这个想法是你的 Circle 类实现了两个不同的接口,它们在非常不同的情况下使用。

回答by Aeolun

The simple answer, in my opinion, and being somewhat new to interfaces myself is that implementing an interface in a class essentially means: "This class MUST define the functions (and parameters) in the interface".

在我看来,我自己对接口有点陌生的简单答案是,在类中实现接口本质上意味着:“这个类必须在接口中定义函数(和参数)”。

From that, follows that whenever a certain class implements the interface, you can be sure you are able to call those functions.

由此可知,每当某个类实现该接口时,您就可以确定您能够调用这些函数。

If multiple classes which are otherwise different implement the same interface, you can 'cast' them all to the interface and call all the interface functions on them, which might have different effects, since each class could have a different implementation of the functions.

如果多个不同的类实现相同的接口,您可以将它们全部“强制转换”到接口并调用它们上的所有接口函数,这可能会产生不同的效果,因为每个类可能具有不同的函数实现。

For example, I've been creating a program which allows a user to generate 4 different kinds of maps. For that, I've created 4 different kind of generator classes. They all implement the 'IGenerator' interface though:

例如,我一直在创建一个程序,它允许用户生成 4 种不同类型的地图。为此,我创建了 4 种不同类型的生成器类。不过,它们都实现了“IGenerator”接口:

public interface IGenerator {
    public void generateNow(int period);
}

Which tells them to define at least a "public generateNow(int period)" function.

这告诉他们至少定义一个“public generateNow(int period)”函数。

Whatever generator I originally had, after I cast it to a "IGenerator" I can call "generateNow(4)" on it. I won't have to be sure what type of generator I returned, which essentially means, no more "variable instanceof Class1", "variable instanceof Class2" etc. in a gigantic if statement anymore.

无论我最初拥有什么生成器,在我将其转换为“IGenerator”之后,我都可以在其上调用“generateNow(4)”。我不必确定我返回的是什么类型的生成器,这基本上意味着,在一个巨大的 if 语句中不再有“类 1 的变量实例”、“类 2 的变量实例”等。

回答by Law Kant Dayal

Note :Interface is used to restrict and access the methods or events etc from differents classes at any cost, It means we can defined many more methods inside any class but when we are calling methods through Interface means we want only other than restricted methods. In the program below User1 can use Read & Write both but User2 can Write and Execute. See this Program below.........

注意:接口用于不惜一切代价限制和访问来自不同类的方法或事件等,这意味着我们可以在任何类中定义更多方法,但是当我们通过接口调用方法时,意味着我们只需要受限方法以外的方法。在下面的程序中,用户 1 可以同时使用读取和写入,但用户 2 可以写入和执行。请参阅下面的此程序.......

namespace ExplConsole
{
    class Program 
    {
        static void Main ()
        {
            System.Console.WriteLine("Permission for User1");
            User1 usr1 = new Test(); // Create instance.
            usr1.Read(); // Call method on interface.
            usr1.Write();
            System.Console.WriteLine("Permission for User2");
            User2 usr2 = new Test();
            usr2.Write();
            usr2.Execute();
            System.Console.ReadKey();
        }
    }
    interface User1
    {
        void Read();
        void Write();
    }
    interface User2
    {
        void Write();
        void Execute();
    }
    class Test : NewTest,User1, User2 
    {
        public void Read()
        {
            Console.WriteLine("Read");
        }
        public void Write()
        {
            Console.WriteLine("Write");
        }
    }
    class NewTest 
    {
        public void Execute()
        {
            Console.WriteLine("Execute");
        }
    }
}

Output:

输出:

    Permission for User1
    Read
    Write
    Permission for User2
    Write
    Execute