Add 'set' to properties of interface in C#

前端 未结 3 479
广开言路
广开言路 2021-02-07 04:16

I am looking to \'extending\' an interface by providing set accessors to properties in that interface. The interface looks something like this:

interface IUser
         


        
相关标签:
3条回答
  • 2021-02-07 04:41

    I don't see any reason why what you have posted shouldn't work? Just did a quick test and it compiles alright, but gives a warning about hiding. This can be fixed by adding the new keyword, like this:

    public interface IMutableUser : IUser
    {
        new string Username { get; set; }
    }
    

    An alternative would be to add explicit set methods; eg:

    public interface IMutableUser : IUser
    {
        void SetUsername(string value);
    }
    

    Of course, I'd prefer to use setters, but if it's not possible, I guess you do what you have to.

    0 讨论(0)
  • 2021-02-07 04:58

    You could use an abstract class:

    interface IUser
    {
        string UserName
        {
            get;
        }
    }
    
    abstract class MutableUser : IUser
    {
        public virtual string UserName
        {
            get;
            set;
        }
    }
    

    Another possibility is to have this:

    interface IUser
    {
        string UserName
        {
            get;
        }
    }
    
    interface IMutableUser
    {
        string UserName
        {
            get;
            set;
        }
    }
    
    class User : IUser, IMutableUser
    {
        public string UserName { get; set; }
    }
    
    0 讨论(0)
  • 2021-02-07 04:58

    You can "override" properties in an interface by explicitly implementing the interfaces. Chris' answer is likely all you'll need for the scenario you've outlined, but consider a slightly more complex scenario, where you need a getter/setter on your class, but the interface only defines the getter. You can get around this by doing the following:

    public class MyUser : IUser
    {
    
        IUser.MyProperty { get { return "something"; } }
    
        public MyProperty { get; set; }
    
    }
    

    By explicitly implementing IUser.MyProperty, you satisfy the contract. However, by providing public MyProperty, the API for your object will never show the explicit interface version, and will always use MyProperty with the get/set.

    0 讨论(0)
提交回复
热议问题