Default implementation of a method for C# interfaces?

后端 未结 6 2005
梦如初夏
梦如初夏 2020-12-24 05:35

Is it possible to define an interface in C# which has a default implementation? (so that we can define a class implementing that interface without implementing that particul

6条回答
  •  萌比男神i
    2020-12-24 05:57

    Not directly, but you can define an extension method for an interface, and then implement it something like this

    public interface ITestUser
    {
        int id { get; set; }
        string firstName { get; set; }
        string lastName { get; set; }
    
        string FormattedName();
    }
    
    static class ITestUserHelpers
    {
        public static string FormattedNameDefault(this ITestUser user)
        {
            return user.lastName + ", " + user.firstName;
        }
    }
    
    public class TestUser : ITestUser
    {
        public int id { get; set; }
        public string firstName { get; set; }
        public string lastName { get; set; }
    
        public string FormattedName()
        {
            return this.FormattedNameDefault();
        }
    }
    

    Edit* It is important that the extension method and the method that you are implementing are named differently, otherwise you will likely get a stackoverflow.

提交回复
热议问题