2017-04-13 75 views
2

我開始我的C#的冒險,不知道所有的工藝,但我已經知道我是什麼努力才達到:C#/類和自定義類型

public class Product 
{ 
    public string Name { get; set; } 
    public double Price { get; set; } 
    //public ??? Category { get; set; } 
} 

「類別」類型應該是一個自定義類型(?),其中有8個可能的字符串值(食品,衣服等)和專門用於這些名稱的圖標(Food - apple.jpg,Clothes - tshirt.jpg等)

我該怎麼辦那?

+2

創建類別新的類/接口也,就像產品一樣。 – Anil

+3

再上課。一個類是一個類型。不過,並非所有類型都是類。 –

+1

看看任何C#教程或任何你喜歡的書。創建一個新類是* any *面向對象類的基礎,因此可以在* every * tutorial/book中解釋。 – HimBromBeere

回答

4

通常情況下,有固定的工作時尺寸類別(您的情況使用8)我們用enum類型:

public enum ProductCategory { 
    Food, 
    Clothes, 
    //TODO: put all the other categories here 
    } 

加起來圖標,字符串等,我們可以實現擴展方法

public static class ProductCategoryExtensions { 
    // please, notice "this" for the extension method 
    public static string IconName(this ProductCategory value) { 
     switch (value) { 
     case ProductCategory.Food: 
      return "apple.jpg"; 
     case ProductCategory.Clothes: 
      return "tshirt.jpg"; 
     //TODO: add all the other categories here 

     default: 
      return "Unknown.jpg"; 
     } 
    } 
    } 

最後

public class Product { 
    public string Name { get; set; } 
    public double Price { get; set; } // decimal is a better choice 
    public ProductCategory Category { get; set; } 
    } 

使用

Product test = new Product(); 

    test.Category = ProductCategory.Clothes; 

    Console.Write(test.Category.IconName()); 
-3

所以首先創建一個新的類,你的自定義類型

public class Category { 
    // I recommend to use enums instead of strings to archive this 
    public string Name { get; set; } 
    // Path to the icon of the category 
    public string Icon { get; set; } 
} 

現在,在你的產品,你可以改變行註釋掉到:

// First Category is the type, the second one the Name 
public Category Category { get; set; } 

現在你可以創建一個新產品帶有一個類別:

var category = new Product() { 
    Name = "ASP.NET Application", 
    Price = 500, 
    Category = new Category() { 
    Name = "Software", 
    Icon = "Software.jpg" 
    } 
} 

現在,當您想要使用另一個類別創建另一個產品ry,只需重複此過程即可。您還可以創建一個Categories數組,然後使用數組元素,例如分類=分類[3]。所以你創建一個類別的食物,一個衣服等,將它們存儲在陣列中,並將它們用於您的產品。

+0

你的答案晚於控制檯的答案。而且你還沒有添加任何有用的東西,對嗎? –

+0

@MassimilianoKraus我添加了如何將它們存儲在一個數組中,以訪問這些類型。我還展示瞭如何實現它。 – Larce

0

您可以定義類別類像預定義的值如下:

public class Category 
{ 
    public static Category Food = new Category("Food", "apple.jpg"); 
    // rest of the predefined values 

    private Category(string name, string imageName) 
    { 
     this.ImageName = imageName; 
     this.Name = name; 
    } 

    public string Name { get; private set; } 
    public string ImageName { get; private set; } 
} 

public class Product 
{ 
    public string Name { get; set; } 
    public double Price { get; set; } 
    public Category Category { get; set; } 
} 

然後,在你的代碼,你可以設置這樣的產品:

var product = new Product {Name= "product1", Price=1.2, Category = Category.Food}; 
+0

有8個靜態成員用於班級中的各種類別不是一個好主意。 – sinitram

+0

@sinitram爲什麼不呢? –

+0

@MassimilianoKraus因爲有枚舉,它們非常適合輕量級的狀態信息。 – sinitram