我有一堂课
class Animals
{
class Cat
{
int Rarity
{
get { return 32; }
}
int amount;
int Amount
{
get { return amount; }
set { amount = value; }
}
}
class Dog
{
int Rarity
{
get { return 15; }
}
int amount;
int Amount
{
get { return amount; }
set { amount = value; }
}
}
class Tiger
{
int Rarity
{
get { return 3; }
}
int amount;
int Amount
{
get { return amount; }
set { amount = value; }
}
}
}
如何简化呢?
答案 0 :(得分:1)
您可以创建一个Animal
基类。您可能希望将其设置为abstract
,所以实例化Animal
的唯一方法是创建一个新的派生对象。
abstract class Animal
{
public abstract int Rarity { get; } // Abstract properties must be implemented by derived classes
public int Amount { get; set; }
}
然后,每种不同类型的动物都可以继承Animal
基类。他们每个人都需要覆盖抽象的Rarity
属性。它们每个都具有Amount
类的Animal
属性。
class Cat : Animal
{
public override int Rarity => 32;
}
class Dog : Animal
{
public override int Rarity => 15;
}
class Tiger : Animal
{
public override int Rarity => 3;
}
答案 1 :(得分:0)
我建议您做些继承。创建一个具有所有这些属性的“动物”类。
class Animal
{
int Rarity
{
get;
}
int amount;
int Amount
{
get { return amount; }
set { amount = value; }
}
}
然后您可以创建一个类(即Cat),并使其继承自Animal类。
class Cat : Animal
{
}
您可以对函数执行相同的操作。