[C# Basics] chatGpt takes you to learn C# interface, what application does it have in the game?

What are Interfaces?

In computer programming, an interface is a set of rules or guidelines that define how different software components or systems should interact with each other. It serves as a contract between two or more components, specifying how they should communicate with each other without revealing the underlying implementation details.

An interface defines a standardized set of methods, properties, events, and other members that can be used by other software components or systems. By adhering to a common interface, components can communicate with each other consistently and predictably, even if they were developed by different software vendors or on different platforms.

Interfaces can be used in a variety of programming languages and technologies, including object-oriented programming, web services, and message-based systems. They are particularly useful in large, complex software systems where many different components need to work together seamlessly.

After modification by Grammarly, it is translated by chatGpt as follows:

In computer programming, an interface is a set of rules or guidelines that define how different software components or systems should interact with each other. It acts as a contract between two or more components, specifying how they should communicate with each other, while not revealing the underlying implementation details.

An interface defines a standardized set of methods, properties, events, and other members that can be used by other software components or systems. By adhering to a common interface, components can communicate with each other in a consistent and predictable manner, even if they are developed by different software vendors or on different platforms.

Interfaces are available in a variety of programming languages ​​and technologies, including object-oriented programming, Web services, and message-based systems. They are especially useful for large and complex software systems where many different components need to work together seamlessly.

Defining Interface

In C#, interfaces can be defined in the following ways:

public interface IMyInterface
{
    
    
    // 定义方法签名,但不提供实现
    void MyMethod1();
    
    // 定义带参数的方法签名
    int MyMethod2(string input);
    
    // 定义属性,不包含实现
    string MyProperty {
    
     get; set; }
    
    // 定义事件,不包含实现
    event EventHandler MyEvent;
}

An interface is a purely abstract concept that defines the signature of a set of methods, properties, or events, but does not provide a concrete implementation. An interface is a specification that defines the behavior that a class or struct should implement. A class or struct can implement one or more interfaces and provide corresponding implementations. When implementing an interface, you must provide implementations for the same methods, properties, or events as the interface defines.

Interface Implementation

Next, we will implement the above definitions one by one.

Method 1: Single Interface

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using static Testing;

public class Testing : MonoBehaviour
{
    
    
    private void Start()
    {
    
    
        MyClass myClass=new MyClass();
        TestInterface(myClass);
    }

    private void TestInterface(IMyInterface myInterface)
    {
    
    
        myInterface.TestFunction();
    }
}

public interface IMyInterface{
    
    void TestFunction();}

public class MyClass : IMyInterface
{
    
    
    public void TestFunction()
    {
    
    
        Debug.Log("MyClass.TestFunction()");
    }
}

insert image description here

Method 2: Multiple Interface

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using static Testing;

public class Testing : MonoBehaviour
{
    
    
    private void Start()
    {
    
    
        MyClass myClass=new MyClass();
        TestInterface(myClass);
        
        MySecondClass mySecondClass=new MySecondClass();
        TestInterface(mySecondClass);
    }

    private void TestInterface(IMyInterface myInterface)
    {
    
    
        myInterface.TestFunction();
    }
}

public interface IMyInterface{
    
    void TestFunction();}

public class MyClass : IMyInterface
{
    
    
    public void TestFunction()
    {
    
    
        Debug.Log("MyClass.TestFunction()");
    }
}

public class MySecondClass : IMyInterface
{
    
    
    public void TestFunction()
    {
    
    
        Debug.Log("MySecondClass.TestFunction()");
    }
}

insert image description here

multiple interface implementations

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using static Testing;

public class Testing : MonoBehaviour
{
    
    
    private void Start()
    {
    
    
        MyClass myClass=new MyClass();
        TestInterface(myClass);
    }

    private void TestInterface(IMyInterface myInterface)
    {
    
    
        myInterface.TestFunction();
    }
}

public interface IMyInterface: IMySecondInterface
{
    
     
    void TestFunction();
}

public interface IMySecondInterface
{
    
    
    void SecondTestFunction(int i);
}

public class MyClass : IMyInterface, IMySecondInterface
{
    
    
    public void SecondTestFunction(int i)
    {
    
    

    }

    public void TestFunction()
    {
    
    
        Debug.Log("MyClass.TestFunction()");
    }
}
//下面会提示报错,因为public interface IMyInterface: IMySecondInterface没有实现相应的方法
//public class MySecondClass : IMyInterface{...}

Interface Properties

In C#, you can use interfaces to define interface properties. getThe syntax for defining an interface property is similar to defining a regular property, but the or setaccessor needs to be preceded by the property declaration to specify how the property is accessed. Here is an example using interface properties:

interface IMyInterface
{
    
    
    int MyProperty {
    
     get; set; }
}

class MyClass : IMyInterface
{
    
    
    private int myPropertyValue;

    public int MyProperty
    {
    
    
        get
        {
    
    
            return myPropertyValue;
        }
        set
        {
    
    
            myPropertyValue = value;
        }
    }
}

class Program
{
    
    
    static void Main(string[] args)
    {
    
    
        MyClass myClass = new MyClass();
        //setter
        myClass.MyProperty = 42;
        //getter
        Console.WriteLine(myClass.MyProperty);
    }
}

In the code above, IMyInterfacethe interface defines an MyPropertyinterface property named , which has getand setaccessors. The class then MyClassimplements IMyInterfacethe interface and provides its own implementation to satisfy the interface's properties.

In MyClassa class, MyPropertya property has a private field myPropertyValueas its actual implementation, getaccessors return the value of the field, and setaccessors set the value of the field.

Finally, in Mainthe method, we create an MyClassobject and MyPropertyset its properties to 42. We then output the value of that property, which prints out 42.

define event

The syntax for defining events in a C# interface is as follows:

event EventHandler MyEvent;

Among them, MyEventis the name of the event, EventHandlerand is the event delegation type. Custom delegate types can be used as needed.

When implementing events in the implementing class, you need addto removeadd and remove event handlers using the and keywords, respectively. The following are examples:

public event EventHandler MyEvent
{
    
    
    add
    {
    
    
        // 在事件委托实例中添加事件处理程序
        // 这里可以添加一些逻辑,例如检查订阅者是否已经存在等等
        _myEvent += value;
    }
    remove
    {
    
    
        // 从事件委托实例中移除事件处理程序
        // 这里可以添加一些逻辑,例如检查订阅者是否存在等等
        _myEvent -= value;
    }
}
//实现事件时,通常建议使用私有事件字段来存储事件委托实例,以保证事件的封装性和安全性。
private event EventHandler _myEvent;

public void RaiseEvent()
{
    
    
    // 触发事件, 使用可空运算符 ?. 来避免空引用异常,因为可能没有任何订阅者订阅该事件。
    _myEvent?.Invoke(this, EventArgs.Empty);
}

Note: Implementing classes must explicitly implement the events defined in the interface, even if they do not have any implementation. This is because the interface event is just a contract that requires the implementing class to provide the implementation of the event.

Application Scenario

The following code ignores details that don't need attention.

question

Suppose we create one ( or more ) enemies and one ( or more ) objects that can be damaged by blows. In Unity, the former two objects created by default have their own independent C# scripts and do not share any base classes or Anything, create another character player, now we want this character to be able to deal damage to enemies and objects, what do we do?

First write a solution that most people would think of. We create a flying knife class FlyCutterto represent the subject that causes damage. First obtain the subject, each subject has a corresponding damage function, and then judge.

public class FlyCutter : MonoBehaviour{
    
    
    //通过物理,检查碰撞
    private void OnTriggerEnter2D(Collider2D collider){
    
    
        Enemy enemy = collider.GetComponent<Enemy>();
        if(enemy!=null){
    
    
            //造成伤害
            enemy.Damge();
        }
        
        WUPING wuping = collider.GetComponent<WUPING>();
        if(wuping!=null){
    
    
            //造成伤害
            wuping.Damge();
        } 
    }
}

EnemyCreate scripts representing enemies that can effectively be dealt damage

public class Enemy : MonoBehaviour{
    
    
   	/*Enemy的主体信息*/
    
    //假设已经有伤害函数,扣血条
    public void Damage(){
    
    ...}
}

objects that can be damaged

public class WUPING : MonoBehaviour{
    
    
    /*WUPING的主体信息与其他额外的操作,比如打开,盗窃,陷阱等等*/
    
    public void Damage(){
    
    ...}
}

I thought it would be enough to add one by one of the above ones? But, you still think too simple! ! !

If we do this, don't we have to consider all the subjects that may be injured, what will happen if we change the weapon? Shouldn't it be repeated?

Solutions

  • When asked about the word independent ->接口
  • How do characters harm other subjects?

So we can create a unified damage interface in a separate scriptIDamageable

public interface IDamageable{
    
    
	void Damage();
}

Let enemies and objects implement this interface

public class Enemy : MonoBehaviour,IDamageable{
    
    
    public void Damage(){
    
    ...}
}

public class WUPING : MonoBehaviour,IDamageable{
    
    
    public void Damage(){
    
    ...}
}

Now we can make our throwing knife simple.

public class FlyCutter : MonoBehaviour{
    
    
    //通过物理,检查碰撞
    private void OnTriggerEnter2D(Collider2D collider){
    
    
        IDamageable damageable = collider.GetComponent<IDamageable>();
        if(damageable!=null){
    
    
            //造成伤害
            damageable.Damge();
        }
    }
}

Other application scenarios

When C#writing games, interfaces are a very useful tool that can help you manage and organize your code. Here are some game scenarios where you can use interfaces:

  1. Character controllers: If you're writing a character controller, you can use interfaces to define common methods such as move, attack, hurt, and die . Each actor can implement these interfaces and override methods to achieve specific behaviors.
  2. Item system: If you are writing an item system, you can use interfaces to define common item interfaces such as use, discard, and exchange . This way, each item can implement these interfaces and override methods to achieve specific behaviors.
  3. Task system: If you are writing a task system, you can use interfaces to define common task interfaces such as accept, complete, and fail . Each task can implement these interfaces and override methods to achieve specific behavior.
  4. State Machines: If you are writing a state machine, you can use interfaces to define common state interfaces such as entry, exit, and update . Each state can implement these interfaces and override methods to achieve specific behavior.
  5. Network communication: If your game needs to communicate with other players or servers, you can use interfaces to define common network interfaces, such as connecting, sending and receiving data . Each network module can implement these interfaces and override methods to achieve specific behaviors.

In short, interfaces can play a role in many scenarios in the game, and can help you organize and manage your code better, making your game easier to maintain and expand.

Guess you like

Origin blog.csdn.net/kokool/article/details/129798445