C#Interface and abstract class learning notes

Keywords: C# Attribute

Extract this note from: https://www.cnblogs.com/solan/archive/2012/08/01/CSharp06.html And record the learning process for future reference.

Summary:

Abstract class: A special class that can define methods with implementation or method contracts that are not implemented. It cannot be instantiated by itself but can only be instantiated in a derived class.Interface: one to one

Group method signatures are named uniformly, can only define unimplemented method contracts, cannot be instantiated themselves, and can only be instantiated in implementation classes.

Both can have some data members (e.g., attributes), which appear to have the same "contract" functionality but have different requirements for their derived classes (implementation classes), so what exactly are they?

What are the similarities and differences?The following four aspects will explain their similarities and differences.

Definition

Abstract classes cannot be instantiated.The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share. It is to abstract a class and either implement it or not.Use the keyword Abstract

Define.

The following defines an abstract class:

public abstract class Code_06_03
{
}

Look at the generated IL from ISDASM:

.class abstract auto ansi nested public beforefieldinit Code_06_03
       extends [mscorlib]System.Object
{
} // end of class Code_06_03

You can see that the abstract class actually inherits the System.Object class and the compiler generates a default constructor for it.

An interface is a uniform naming of a set of method signatures, a definition of a set of behavior specifications, and a definition using the keyword interface.

The following defines an interface:

public interface ICode_06_01
{
}

* Look at the generated IL through ISDASM:

.class interface abstract auto ansi nested public ICode_06_01
{
} // end of class ICode_06_01

You can see that an interface actually treats it as an abstract class, but there is no constructor.Whether abstract classes have constructors or interfaces do not have constructors, they cannot be instanced

Chemical.

2. Membership differences

Abstract class description:

1) An abstract method can be defined. It is not implemented specifically, it is just a contract of the method, and it is overridden in subclasses.Abstract classes can override that the virtual method of a parent class is abstract.

2) A non-abstract method can be defined, but it is required to be implemented concretely. If the method is virtual, it can be overridden in subclasses.

3) You can define fields, attributes, Abstract attributes, events, and static members.

The following is an extension to the class Code_06_03:

    class Program
    {
        /// <summary>
        /// abstract class
        /// </summary>
        public abstract class Code_06_03
        {
            Dictionary<Guid, string> root = new Dictionary<Guid, string>();
            public string Sex { get; set; }
            public abstract string Address { get; }
            public abstract int Add(int a, int b);

            protected virtual string GetAddress(string addressID)
            {
                return addressID + " Guangdong";
            }

            public void AddRoot(Guid id, string rootName)
            {
                root.Add(id, rootName);
                OnAddRoot();
            }

            public event EventHandler AddRootEvent;

            void OnAddRoot()
            {
                AddRootEvent?.Invoke(this, null);
            }

            public string this[Guid key]
            {
                get
                {
                    return root[key];
                }
                set
                {
                    root[key] = value;
                }
            }
        }

        static void Main(string[] args)
        {

        }
    }

2.1 public abstract int Add(int a, int b); IL:

.method public hidebysig newslot abstract virtual 
        instance int32  Add(int32 a,
                            int32 b) cil managed
{
} // end of method Code_06_03::Add

The compiler treats the Add method as a virtual method that can be overridden in subclasses.

IL for 2.2 virtual method protected virtual string GetAddress(string addressID):

.method family hidebysig newslot virtual 
        instance string  GetAddress(string addressID) cil managed
{
  // Skip
} // end of method Code_06_03::GetAddress

It is a virtual method, so the compiler does not treat it specially.

IL of 2.3 method public void AddRoot(Guid id, string rootName):

.method public hidebysig instance void  AddRoot(valuetype [mscorlib]System.Guid id,
                                                string rootName) cil managed
{
  // Skip
} // end of method Code_06_03::AddRoot

It is also a common object method.

Interface description:

1) Attributes and indexers can be defined, but fields cannot be defined.

2) Events can be defined.

3) Method can be defined, just a convention of method signature, and must not be implemented. The method is implemented in the implementation class, which is somewhat similar to the abstract method of an abstract class.

4) Virtual methods cannot be defined.

5) No static members can be defined.

6) Interface members are open by default and must not have access modifiers.

The following is an extension to class Code_06_01:

    class Program
    {
        /// <summary>
        /// Interface
        /// </summary>
        public interface ICode_06_01
        {
            string Name { get; set; }
            int Add(int a, int b);
            event EventHandler AddEvent;
        }

        static void Main(string[] args)
        {

        }
    }

2.4 Method int Add(int a, int b); IL:

.method public hidebysig newslot abstract virtual 
        instance int32  Add(int32 a,
                            int32 b) cil managed
{
} // end of method ICode_06_01::Add

You can see that at the time of definition, we did not specify an accessible modifier for it (the compiler does not allow us to specify an accessible modifier explicitly), but the compiler defaults to its access level

Instead of specifying public, consider it an abstract virtual method.

As for member attributes and events, the compiler treats them as normal object attributes and object events, and generates corresponding get/set and add/remove methods for them, without exception

Department.

3. Differences in ways of implementation

Abstract class implementation:

Since abstract classes are classes, their implementation is like common inheritance, where subclasses derive public members of abstract classes and override some members, such as virtual methods and abstracts

Method, etc.

The following is an implementation of the Code_06_03 class:

    class Program
    {
        /// <summary>
        /// abstract class
        /// </summary>
        public abstract class Code_06_03
        {
            Dictionary<Guid, string> root = new Dictionary<Guid, string>();
            public string Sex { get; set; }
            public abstract string Address { get; }

            /// <summary>
            /// Abstract method ADD
            /// </summary>
            /// <param name="a"></param>
            /// <param name="b"></param>
            /// <returns></returns>
            public abstract int Add(int a, int b);

            /// <summary>
            /// Virtual method GetAddress
            /// </summary>
            /// <param name="addressID"></param>
            /// <returns></returns>
            protected virtual string GetAddress(string addressID)
            {
                return addressID + " Guangdong";
            }

            public void AddRoot(Guid id, string rootName)
            {
                root.Add(id, rootName);
                OnAddRoot();
            }

            public event EventHandler AddRootEvent;

            void OnAddRoot()
            {
                AddRootEvent?.Invoke(this, null);
            }

            public string this[Guid key]
            {
                get
                {
                    return root[key];
                }
                set
                {
                    root[key] = value;
                }
            }
        }

        /// <summary>
        /// Implementation of abstract classes
        /// </summary>
        public class Code_06_04 : Code_06_03
        {
            public override int Add(int a, int b)
            {
                return a + b;
            }
            protected override string GetAddress(string addressID)
            {
                return "GuangDong";
            }

            readonly string addressPrefix = "China ";
            public override string Address
            {
                get { return addressPrefix; }
            }
        }

        static void Main(string[] args)
        {

        }
    }

* Look at the generated IL through ISDASM:

You can see that class Code_06_04 is the standard way to inherit class Code_06_03, both overridden methods Add and GetAddress are common object methods, but they are still

Treat it as a dummy.

IL of method Add 3.1:

.method public hidebysig virtual instance int32 
        Add(int32 a,
            int32 b) cil managed
{
  // Skip
} // end of method Code_06_04::Add

IL of 3.2 method GetAddress:

.method family hidebysig virtual instance string 
        GetAddress(string addressID) cil managed
{
  // Skip
} // end of method Code_06_04::GetAddress

Because these two methods maintain the properties of virtual methods, they can also be overridden for subclasses of the Code_06_04 class.Attribute member Address Also here

Is a common object property.

Interface implementation

The implementation of the interface is similar to that of an abstract class. The following is the implementation of the interface ICode_06_01:

    class Program
    {
        /// <summary>
        /// Interface
        /// </summary>
        public interface ICode_06_01
        {
            string Name { get; set; }
            int Add(int a, int b);
            event EventHandler AddEvent;
        }

        /// <summary>
        /// Implementation of interface
        /// </summary>
        public class Code_06_02 : ICode_06_01
        {
            public string Name { get; set; }

            public int Add(int a, int b)
            {
                OnAdded();
                return a + b;
            }

            public event EventHandler AddEvent;

            void OnAdded()
            {
                AddEvent?.Invoke(this, null);
            }
        }

        static void Main(string[] args)
        {

        }
    }

* Look at the generated IL through ISDASM:

It is not very different from ordinary classes, but it is clear that the interface ICode_06_01 has been implemented. Take a look at its IL:

.class auto ansi nested public beforefieldinit Code_06_02
       extends [mscorlib]System.Object
       implements LinkTo.Test.InterfaceAndAbstractClass.Program/ICode_06_01
{
} // end of class Code_06_02

You can see that the class Code_06_02 not only inherits from the System.Object class, but also implements the interface ICode_06_01.Let's look again at the methods in the interface.

How is the translator handled?

IL of method Add 3.3:

.method public hidebysig newslot virtual final 
        instance int32  Add(int32 a,
                            int32 b) cil managed
{
  // Skip
} // end of method Code_06_02::Add

The compiler considers the Add method to be virtual.For attributes and events, it is still a common implementation, such as get/set, add/remove.In addition, the interface supports

Displays the implementation interfaces, and the implementations of the Code_06_02 class-to-interface discussed above default to implicit implementations.

Within the implementation class of an interface, there can be a method with exactly the same name (including signature) as a method of the interface, but the method required to be implemented on the interface must be explicit

Indicates the implementation, as follows:

        public int Add(int a, int b)
        {
            return a + b;
        }

        int ICode_06_01.Add(int a, int b)
        {
            OnAdded();
            return a + b;
        }

You can see that the implementation is preceded by an interface name and a dot (ICode_06_01.) and that the compiler does not have an accessible modifier on the method

private processing.So how can I call the interface method that displays the implementation?You can turn an object that implements a class into an interface variable, then call the appropriate method for that variable, as follows

Code:

        static void Main(string[] args)
        {
            Code_06_02 code0602 = new Code_06_02();
            ICode_06_01 icode0602 = code0602;
            var result = icode0602.Add(1, 2);
            Console.WriteLine($"Result={result}");
            Console.Read();
        }

Implementations of abstract classes cannot be displayed.

4. Differences in Application

1) An abstract class retains some of the attributes of a common class and defines method behavior that may have been implemented. Within a method, data members such as attributes can be manipulated, and methods can

Communicate with each other.Interfaces are just signatures that define methods, like rules, but conventions, and are not implemented.

2) Derived classes of abstract classes can get some members of abstract classes intact, and implementation classes of interfaces must override them if they want data members of interfaces.

3) A class can only inherit from one class (including Abstract classes), but can implement multiple interfaces, and can implement multiple interfaces simultaneously on the basis of inheriting a base class.

4) sealed seals cannot be used on abstract classes and interfaces. In fact, both of them are intended to be inherited and implemented by other classes. sealed is meaningless for them.

5) Abstract classes can implement interfaces.

6) Abstract classes are more used for "duplicating copies of objects", which is often referred to as "subclasses have an is a relationship with their parent". It focuses more on the overall characteristics of an object.Interface

There is a greater tendency to favor a series of method operations that have the same object of action and are isolated from each other in the current context.

7) Sometimes abstract classes can be interchanged with interfaces.

Explain interfaces and abstract classes to us through examples of the common bride-to-bride connections in life: Matchmaker arranges for wooer meetings and directs conversations

Convenience.

The following code demonstrates that no interface is used to match the bride of an abstract class:

    class Program
    {
        /// <summary>
        /// Red Daughters
        /// </summary>
        public class Matchmaker
        {
            string message;

            /// <summary>
            /// Situational, polite conversation guidance
            /// </summary>
            public void Teach()
            {
                message = "There was once a true love in front of me...";
                Wooer wooer = new Wooer();
                wooer.Say(message);
            }
        }

        /// <summary>
        /// Affinity Class
        /// </summary>
        public class Wooer
        {
            /// <summary>
            /// Spoken and polite conversations
            /// </summary>
            /// <param name="message"></param>
            public void Say(string message)
            {
                Console.WriteLine(message);
            }
        }

        static void Main(string[] args)
        {
            #region Don't use bridesmaids for interfaces and abstract classes
            Matchmaker matchmaker = new Matchmaker();
            matchmaker.Teach();
            Console.Read();
            #endregion
        }
    }

The results are as follows:

There is no problem with the above functions, but if a loved one wants to add a little more body movement or artistic display to win the other's favor, the bride will have to change.So, Red Maid

Build a dating platform...

The following code demonstrates using interfaces to connect with the bride of abstract classes:

    class Program
    {
        /// <summary>
        /// Red Daughters
        /// </summary>
        public class MatchmakerNew
        {
            string message;
            /// <summary>
            /// Situational, polite conversation guidance
            /// </summary>
            public void Teach(IWooer wooer)
            {
                message = "There was once a true love in front of me...";
                wooer.Say(message);
            }
        }
        /// <summary>
        /// Affinity Interface
        /// </summary>
        public interface IWooer
        {
            /// <summary>
            /// House ticket...
            /// </summary>
            string Message { get; }
            /// <summary>
            /// Can sing and dance...
            /// </summary>
            void Action();
            /// <summary>
            /// Sweet words...
            /// </summary>
            /// <param name="message"></param>
            void Say(string message);
        }

        /// <summary>
        /// Male Partner Implementation Class
        /// </summary>
        public class ManWooer : IWooer
        {
            public string Message
            {
                get { return "Marry me. There's nothing to get tickets for my house."; }
            }
            public void Action()
            {
                Console.WriteLine("Wolf disco......");
            }
            public void Say(string message)
            {
                Action();
                Console.WriteLine(message + Message);
            }
        }

        /// <summary>
        /// Friends Implementation Class
        /// </summary>
        public class WomanWooer : IWooer
        {
            public string Message
            {
                get { return "Married me, this cow and the hill behind you are yours."; }
            }
            public void Action()
            {
                Console.WriteLine("Hate late meeting...");
            }
            public void Say(string message)
            {
                Action();
                Console.WriteLine(message + Message);
            }
        }

        static void Main(string[] args)
        {
            #region Use bridesmaids for interfaces and abstract classes
            MatchmakerNew matchmakerNew = new MatchmakerNew();

            //Male married
            IWooer manWooer= new ManWooer();
            matchmakerNew.Teach(manWooer);
            manWooer.Say("Dear:");
            Console.WriteLine();

            //Big Marriage
            IWooer womanWooer = new WomanWooer();
            matchmakerNew.Teach(womanWooer);
            womanWooer.Say("Dear:");
            
            Console.Read();
            #endregion
        }
    }

The results are as follows:

Posted by kman on Sun, 29 Dec 2019 20:46:15 -0800