开发者

polymorphism, inheritance in c# - base class calling overridden method?

开发者 https://www.devze.com 2022-12-30 07:22 出处:网络
This code doesn\'t work, but hopefully you\'ll get what I\'m trying to achieve here.I\'ve got a Money class, which I\'ve taken from http://www.noticeablydifferent.com/CodeSamples/Money.aspx, and exten

This code doesn't work, but hopefully you'll get what I'm trying to achieve here. I've got a Money class, which I've taken from http://www.noticeablydifferent.com/CodeSamples/Money.aspx, and extended it a little to include currency conversion.

The implementation for the actual conversion rate could be different in each project, so I decided to move the actual method for retrieving a conversion rate (GetCurrencyConversionRate) into a derived class, but the ConvertTo method contains code that would work for any implementation assuming the derived class has overriden GetCurrencyConversionRate so it made sense to me to keep it in the parent class? So what I'm trying to do is get an instance of SubMoney, and be able to call the .ConvertTo() method, which would in turn use the overriden GetCurrencyConversionRate, and return a new instance of SubMoney.

The problem is, I'm not really understanding some concepts of polymorphism and inheritance yet, so not quite sure what I'm trying to do is even possible in the way I think it is, as what is currently happening is that I end up with an Exception where it has used the base GetCurrencyConversionRate method instead of the derived one. Something tells me I need to move the ConvertTo method down to the derived class, but this seems like I'll be duplicating code in multiple imp开发者_运维百科lementations, so surely there's a better way?

public class Money
{
    public CurrencyConversionRate
    {
        get
        {
            return GetCurrencyConversionRate(_regionInfo.ISOCurrencySymbol);
        }
    }

    public static decimal GetCurrencyConversionRate(string isoCurrencySymbol)
    {
        throw new Exception("Must override this method if you wish to use it.");
    }

    public Money ConvertTo(string cultureName)
    {          
        // convert to base USD first by dividing current amount by it's exchange rate.
        Money someMoney = this;
        decimal conversionRate = this.CurrencyConversionRate;
        decimal convertedUSDAmount = Money.Divide(someMoney, conversionRate).Amount;

        // now convert to new currency
        CultureInfo cultureInfo = new CultureInfo(cultureName);
        RegionInfo regionInfo = new RegionInfo(cultureInfo.LCID);
        conversionRate = GetCurrencyConversionRate(regionInfo.ISOCurrencySymbol);
        decimal convertedAmount = convertedUSDAmount * conversionRate;
        Money convertedMoney = new Money(convertedAmount, cultureName);
        return convertedMoney;
    }
}

public class SubMoney
{
    public SubMoney(decimal amount, string cultureName) : base(amount, cultureName) {}

    public static new decimal GetCurrencyConversionRate(string isoCurrencySymbol)
    {
        // This would get the conversion rate from some web or database source
        decimal result = new Decimal(2);
        return result;
    }
}


A static method can only be used by specifying the exact class where it's declared. There is no way to involve inheritance in that.

Make the Money class abstract so that it has to be derived to be used. Make the GetCurrencyConversionRate method abstract (which also automatically makes it virtual). Make the SubMoney class inherit Money and override the GetCurrencyConversionRate method:

public abstract class Money {

  public abstract decimal GetCurrencyConversionRate(string isoCurrencySymbol);

  ...

}

public class SubMoney : Money {

  public override decimal GetCurrencyConversionRate(string isoCurrencySymbol) {
    ...
  }

}

As the method is declared in the Money class, it knows about it and can use it. The actual class that you create instances of is the derived class like SubMoney so there is always an implementation of the method.


Another option is to use the Strategy Pattern, whereby you abstract the algorithm for conversion, which is implemented as its own class. You can then switch out the implementation of the converter at runtime. This allows you to take advantage of "composition over inheritance" by swapping algorithms at runtime using some form of dependency injection.

After designing a complex system, I have definitely learned the benefits of composition over inheritance. Frankly, inheritance is only truly useful when your goal is to increase code reuse via polymorphism. Once you get into complex type hierarchies where the inheritance chain is over four or five levels deep you end up butting heads with crosscutting concerns (which leads to lots of copypasting of very similar code that cannot be shared amongst sibling types). Composition allows for simpler designs, ease of configuration (think of designing a complex form in WPF using xaml), testing, etc etc.

Anyhow, just to give you something to scratch your head over.


You aren't using Inheritance/Overriding at all, you are hiding the method.

public abstract class Money
{
    public CurrencyConversionRate
    {
        get
        {
            return GetCurrencyConversionRate(_regionInfo.ISOCurrencySymbol);
        }
    }

    public abstract decimal GetCurrencyConversionRate(string isoCurrencySymbol);

    public Money ConvertTo(string cultureName)
    {          
        // convert to base USD first by dividing current amount by it's exchange rate.
        Money someMoney = this;
        decimal conversionRate = this.CurrencyConversionRate;
        decimal convertedUSDAmount = Money.Divide(someMoney, conversionRate).Amount;

        // now convert to new currency
        CultureInfo cultureInfo = new CultureInfo(cultureName);
        RegionInfo regionInfo = new RegionInfo(cultureInfo.LCID);
        conversionRate = GetCurrencyConversionRate(regionInfo.ISOCurrencySymbol);
        decimal convertedAmount = convertedUSDAmount * conversionRate;
        Money convertedMoney = new Money(convertedAmount, cultureName);
        return convertedMoney;
    }
}

public class SubMoney : Money
{
    public SubMoney(decimal amount, string cultureName) : base(amount, cultureName) {}

    public override decimal GetCurrencyConversionRate(string isoCurrencySymbol)
    {
        // This would get the conversion rate from some web or database source
        decimal result = new Decimal(2);
        return result;
    }
}

If you declare a method as abstract, inheriting classes have to override this method, by this you enforce the custom code. Of course, your SubMoney class has to inherit Money to do this.


GetCurrencyConversionRate is static. Cannot be overriden.

0

精彩评论

暂无评论...
验证码 换一张
取 消