【问题标题】:IPersistable Interface - Any trick or hack to change field nameIPersistable 接口 - 更改字段名称的任何技巧或技巧
【发布时间】:2012-01-24 11:14:34
【问题描述】:

对于可以保存在持久性介质中的类,我正在创建名为IPersistable 的接口,旨在提供persistenceId

public interface IPersistable
{
    private readonly string persistenceId;
}

当然,我不能这样做,因为接口不允许字段。如果是这样,我会在下面完成它

Public Class Customer
{

 private readonly string persistenceId;

 Public string UserId
   {
     get{return persistenceId};
   }

 Public Customer(string customerId)
  {
    persistenceId = customerId;
  }
}

我已经在继承一个类,因此无法进行多重继承。我可以使用组合,但接口在这里似乎是正确的。向我展示一个巧妙的技巧来执行上述操作,而不是为每个需要持久化的类添加一个属性。

问题

如果可能,与IPersistable 接口的类是否可以将属性名称(如果 persistenceId 是属性)更改为有意义的名称?

【问题讨论】:

  • 接口是对外使用的公共合约,为什么使用这个接口的人需要关心私有字段叫什么?您不能更改公共成员名称,否则会违反合同。
  • 您似乎在这个私有字段前面加上了类名或从类名推导出来的东西。这是不必要的; Customer.id 似乎比 Customer.customerId 更好,并且还避免了您想要重命名每个类的属性(无论如何这是不可能的)。另外,你知道你可以在接口中拥有属性吗?

标签: c# inheritance properties interface


【解决方案1】:

如果您希望能够保留现有类型(例如 int 或 string),那么接口将无济于事。也许你可以使用包装类而不是接口?比如:

class Persistable<T>
{
    public Persistable<T>(string PersistanceId, T Data)

    public readonly string PersistanceId;
    public readonly T Data;
}

【讨论】:

    【解决方案2】:

    怎么了?

    public interface IPersistable
    {
        String PersistenceId { get; }
    }
    
    Public Class Customer : IPersistable
    {
    
        public string PersistenceId { get; private set; }
    
        public string UserId { 
             get { return PersistenceId; } 
        }
      .
      .
      .
    }
    

    【讨论】:

    • 这意味着 Customer.UserIdCustomer.PersistenceId 为什么我想要 2 个 id 做同样的事情。
    【解决方案3】:

    试试这样的:

    public interface IPersistable<TType>
    {
       TType PersistenceId { get; }
    }
    
    public abstract PersistableEntity<TType> : IPersistable<TType>
    {
       private TType persistenceId;
    
       public TType PersistenceId
       {
           get { return persistenceId; }
       }
    
       public PersistableEntity(TType persistenceId)
       {
          this.persistenceId = persistenceId;
       }
    }
    
    public class Customer : PersistableEntity<string>
    {
       public Customer(string persistenceId)
         : base(persistenceId)
       {
       }
    }
    

    【讨论】:

    • TIdentity 会更好 ;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-08
    • 2018-06-04
    • 2011-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多