C#将值从抽象类转换回对象

C#将值从抽象类转换回对象,c#,C#,在下面的代码中我需要一些帮助。我试图从继承的类中检索一个值 public abstract class Amount { } public class Quantity : Amount { public decimal quantityDecimal; public Quantity(decimal decimal_qty) { this.quantityDecimal= decimal_qty; } } public cl

在下面的代码中我需要一些帮助。我试图从继承的类中检索一个值

public abstract class Amount
{        
}

public class Quantity : Amount
{
    public decimal quantityDecimal;

    public Quantity(decimal decimal_qty)
    {
        this.quantityDecimal= decimal_qty;
    }
}

public class Portion : Amount
{
    public decimal portionDecimal;

    public Portion (decimal decimal_qty)
    {
        this.portionDecimal= decimal_qty;
    }
}
这就是我根据逻辑计算数量或por的方法

public Amount createAmount(Quantity qty, Portion por)
{
   //sample logic here
   Amount compQuantity = qty;
   Amount comPortion = por;

   Amount compAmount = compQuantity ?? comPortion;
}
这就是我试图以字符串形式检索Amount值的方式,但是我无法返回值。它只是以字符串形式返回Amount类的类型。请帮忙

public string GetAmount(Amount amt)
{
   string return_str = amt.ToString(); //amt has the value but i can not assign it to return_str
   return 
}

您需要将Amount放在基类中以实现您想要的。因此,它被继承到具体的实现数量/部分。 (我不会为此滥用
.ToString()

这里有一个小样本

class Program
{
    static void Main(string[] args)
    {
        var q = new Quantity(15);
        Portion p = null;
        var amount = GetAmount(q, p);
    }

    private static decimal GetAmount(Quantity q, Portion p)
    {
        AmountBase a   = (AmountBase)q ?? p;

        return a.Amount;
    }
}


public abstract class AmountBase
{
    public decimal Amount { get; set; }

    public AmountBase(decimal amount)
    {
        Amount = amount;
    }
}

public class Quantity : AmountBase
{
    public Quantity(decimal amount) : base(amount)
    {

    }
}

public class Portion : AmountBase
{
    public Portion(decimal amount) : base(amount)
    {

    }
}

重写每个类中的
ToString()
函数。当你说
Amount-value
时,你应该明确你到底想检索什么。现在,您的抽象类没有多大用途,因为您只是在继承的类中定义值属性。如果两个派生类都有十进制值,则应该执行与下面的答案类似的操作,在抽象类中定义decimal
Value
属性,然后通过调用派生类上的
base
构造函数进行设置。然后,如果需要特定类型的格式,甚至可以重写抽象类中的
ToString()
方法。所以@gsharp的回答正确地引导了我。为什么这个问题被否决了?谢谢你的回答。我实际上是在寻找这样的解决方案。