我想找出一个很好的方法来解决这个问题.我有一个Customer类实现了ICustomer接口.这个界面有很多属性:
public interface ICustomer { string FirstName {get; set;} string LastName {get; set;} }
我只希望某些类能够设置这些属性;即项目中的这些课程.所以我想到了内置的设置器:
public class Customer : ICustomer { string FirstName {get; internal set;} string LastName {get; internal set;} }
我想在该界面中将该setter标记为内部,所以没有人可以实现ICustomer,而在程序集之外的人修改了这些属性.有没有办法做到这一点?
解决方法
界面中的属性应该是只读的.即使接口中没有定义,实现接口的具体类也可以使用setter.
public interface ICustomer { string FirstName { get; } string LastName { get; } } public class Customer : ICustomer { public string FirstName { get; internal set; } public string LastName { get; internal set; } }
如果通过界面暴露设置器是非常重要的,而不是使接口完全只读,那么可以使用以下内容:
public interface IReadCustomer { string FirstName { get; } string LastName { get; } } internal interface IWriteCustomer { string FirstName { set; } string LastName { set; } } internal interface IReadWriteCustomer : IReadCustomer,IWriteCustomer { } public class Customer : IReadWriteCustomer { private string _firstName; private string _lastName; public string FirstName { get { return _firstName; } internal set { _firstName = value; } } public string LastName { get { return _lastName; } internal set { _lastName = value; } } string IReadCustomer.FirstName { get { return FirstName; } } string IReadCustomer.LastName { get { return LastName; } } string IWriteCustomer.FirstName { set { FirstName = value; } } string IWriteCustomer.LastName { set { LastName = value; } } }