2015-11-02 82 views
-3

我想打印价格在10到50欧元之间的所有产品。 我在main中创建了2个产品,我为了进行验证而调用了类Product中的方法。但是它每次都会给我else分支,“没有产品”。我明白我做错了什么,我创建了一个来自类Product的对象引用,然后我调用该方法,但它给了我错误的输出,因为在该方法中,我创建了另一个对象,对于此对象,此价格为0,因此它向我显示了该事情。 但我该如何解决这个问题? 这里有类: 产品类:如何解决C#中的空对象引用?

class Product 
{ 
    public int ProductId; 
    public string SKU; 
    public string Name; 
    public decimal Price; 
    public string Description; 
    public string Producer; 
    public virtual decimal GetPrice() 
    { 
     return Price; 
    } 
    public virtual String GetName() 
    { 
     return Name; 
    } 
    public void PrintPrice() 
    { 
     Product f = new Product(); 
     if (f.GetPrice() > 10 && f.GetPrice() < 50) 

      Console.WriteLine("Product: {0}", f.GetName()); 

     else 
      Console.WriteLine("No products priced between 10 and 50 lei."); 
    } 
    public Product() { } 

主要的,我一直在创建对象:

static void Main(string[] args) 
    { 
     Product f = new Food(1, "green", "Papa", 15, "Good Quality", "Sana"); 
     Product f1 = new Food(2, "white", "Papa1", 45, "Bad Quality", "Ariel"); 

     f.PrintPrice(); 
     f1.PrintPrice(); 
    } 

和我也有食品类,但它继承只有产品类所以这里没有关系。所以我能做什么?谢谢。

+1

if .GetPrice()> 10 && this.GetPrice()<50),删除f 宣言。 – Oscar

+4

用'this'替换'f'。 –

+0

@PatrickHofman完全删除'f.'。 – DavidG

回答

3
public void PrintPrice() 
    { 
     Product f = new Product(); 
     .... 
    } 

目前,f是一个新的产品,而不

你应该这样做

public void PrintPrice() 
{ 
    if (this.GetPrice() > 10 && this.GetPrice() < 50) 

     Console.WriteLine("Product: {0}", this.GetName()); 

    else 
     Console.WriteLine("No products priced between 10 and 50 lei."); 
} 
-1

你没有一个值分配给价格的任何属性(包括没有价格)如果(f.GetPrice()> 10 && f.GetPrice()<50)应该是:if(this(this this)is 0,then have the“No products”..试着给产品分配一个值

相关问题