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