开发者

Setting default value for properties of Interface?

开发者 https://www.devze.com 2023-04-12 22:29 出处:网络
I have an Interface which contains one property. I need to set the default value for that property. How to do that?. Also is it good practice to have a default value for a property in Interface? or he

I have an Interface which contains one property. I need to set the default value for that property. How to do that?. Also is it good practice to have a default value for a property in Interface? or here using an abstra开发者_JS百科ct class instead is a apt one?


You can't set a default value to a property of an interface.

Use abstract class in addition to the interface (which only sets the default value and doesn't implement anything else):

    public interface IA {
        int Prop { get; }

        void F();
    }

    public abstract class ABase : IA {
        public virtual int Prop
        {
            get { return 0; }
        }

        public abstract void F();
    }

    public class A : ABase
    {
        public override void F() { }
    }


With C#8, interfaces can have a default implementation. https://devblogs.microsoft.com/dotnet/default-implementations-in-interfaces/


Interfaces contain no implementation. All they do is state member signatures.

An implementation of an interface is free to have whatever default value it likes for any property.

E.g. an abstract class can return a default value for any of it's properties.

0

精彩评论

暂无评论...
验证码 换一张
取 消