C# 我希望一个继承的类只设置,另一个继承的类只得到



我有一个名为ModelDonation.cs的.cs文件,它包含3个类。一个是我的基类,我希望我的其他类从中继承。然后我有两个从基类继承的类。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GiftAidCalculator.TestConsole
{
     abstract class Donation
    {
        private decimal DonationAmountTotal;
        public virtual decimal donationAmountTotal
        {
            get
            {
                return donationAmountTotal = DonationAmountTotal;
            }
            set
            {
                DonationAmountTotal = donationAmountTotal;
            }
        }
        private decimal VAT;
        public virtual decimal vAT
        {
            get
            {
                return vAT = VAT;
            }
        }      
    }
     class Donor : Donation
     {
         public override decimal vAT
         {
             get
             {
                 return vAT = VAT;
             }
         }
     }
     class SiteAdministrator : Donation
     {
         public decimal vAT
         {
             get
             {
                 return vAT = VAT;
             }
             set
             {
                 VAT = vAT;
             }
         }
     } 
}

我不希望我的捐赠者类别能够设置增值税。捐赠者可以获取增值税以查看捐赠的组成。

我希望站点管理员能够设置和获取增值税。他是改变增值税税率的人。

我的问题是在 C# 中使用继承。我不确定如何以我想要的方式实现它。

谁能帮忙?

谢谢!

你的问题在于使用继承来解决最好通过使用接口和组合来解决的问题。

定义两个接口:

public interface IVatControllable
{
    decimal Vat { get; set; }
}
public interface IVatGettable
{
    decimal Vat { get; }
}

并让您的类实现正确的接口:

public class Donor : IVatGettable
{
    public decimal Vat { get { ... } }
}

等。

在这种情况下,没有必要通过继承使您的设计复杂化。

使属性 b 仅获取,并将一个方法添加到新接口。

例:

/* This isnterface holds method that suitable 
 * for administration related tasks
**/
public interface IAdministrator {
   void SetVAT(..);
  ...
  //other Administration related methods
}
/* Generic, abstract class for Donation description and management*/
abstract class Donation {
   public virtual decimal vAT
   {
        get
        {
            return vAT = VAT;
        }
    }      
}
/*Administrator is able act as Donation AND as Administrator*/
public class Administrator : IAdministrator, Donation
{
}

因此,在您的代码中也表现出可信赖性的逻辑分离。 Administrator Donator,但Administrator也是如此。

如果您希望将

增值税获取/设置属性保留在一起,则可以定义两个接口:

public interface IVATFullAccess {
    public decimal VAT { get; set; }
};
public interface IVATReader {
    public decimal VAT { get; }
};
public class Administrator: IVATFullAccess,... { ... } // has full access to VAT
public class Donation : IVATReader,...  { ... } // has read-only access to VAT

可以扩展此技术以包含其他访问控制 - C# 允许类从多个接口继承(类似于C++多个继承)。

public class Administrator: IVATFullAccess, IAccountCreate, IEmailNotify, ... {}
public class Donation : IVATReader, IAccountIndex {}

如果您来自像C++这样的语言,请将接口视为虚拟基类。

最新更新