Add 'set' to properties of interface in C#

前端 未结 3 482
广开言路
广开言路 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: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.

提交回复
热议问题