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

发布于 2024-08-15 13:41:43 字数 67 浏览 2 评论 0原文

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

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#

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

寂寞笑我太脆弱 2024-08-22 13:41:43

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

然后,您可以编写该类的“具体”实现来与 MySQL 等一起使用。不过,您的 UI 应该仅指界面。

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

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

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.

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

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

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.

忘羡 2024-08-22 13:41:43

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

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

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

这是一个示例实现。

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);
    }
}

更新函数有一个简化的弹簧力更新,更容易理解。

这在几个方面都有帮助。

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

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

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

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:

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.

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.

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

寄离 2024-08-22 13:41:43

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

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");
        }
    }
}

输出:

    Permission for User1
    Read
    Write
    Permission for User2
    Write
    Execute

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.........

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
你穿错了嫁妆 2024-08-22 13:41:43

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

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");
    }
}

更新

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

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; }
}

Interfaces simply define a contract of 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)

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; }
}
羁〃客ぐ 2024-08-22 13:41:43

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

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

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

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

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

这只是一个示例。

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

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

因此,该引擎需要您实现规则。当然,还会有多重继承,因为您肯定希望不止一个规则。

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

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.

菩提树下叶撕阳。 2024-08-22 13:41:43

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

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);
}

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

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.

骄傲 2024-08-22 13:41:43

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

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

接口的目的是您可以将实现接口 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.

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.

The purpose of interfaces is that you can implicitly cast a class that implements interface I to an instance of interface 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.
遗弃M 2024-08-22 13:41:43

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

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

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

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

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

这告诉它们至少定义一个“publicgenerateNow(int period)”函数。

无论我最初拥有什么生成器,在将其转换为“IGenerator”后,我都可以对其调用“generateNow(4)”。我不必确定我返回的生成器类型,这本质上意味着在巨大的 if 语句中不再有“variable instanceof Class1”、“variable instanceof Class2”等。

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:

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

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

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.

许一世地老天荒 2024-08-22 13:41:43

看一下您熟悉的东西 - 即 C# 中的 List 集合。列表定义 IList 接口,通用列表定义 IList 接口。 IList公开了诸如Add、Remove之类的函数,并且List实现了这些函数。还有一些 BindingList 以稍微不同的方式实现 IList。

我还推荐Head First设计模式。代码示例采用 Java 语言,但很容易翻译成 C#,而且它们还将向您介绍接口和设计模式的真正威力。

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.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文