我对C#很陌生,而且我一直在试图弄清楚如何实现与实例相关的特定设计模式以及从派生类返回相同值的静态属性。似乎可能存在限制,以防止这种情况发生,所以我想解释我的问题,看看是否有人对如何解决这个问题有任何想法。
public class Resource {
protected static float s_unitMass = 1.0f;
protected static string s_name = "<Resource>";
public int quantity;
// Class Convenience
static public float GetUnitMass() {
return s_unitMass;
}
static public string GetName() {
return s_name;
}
// Instance Convenience
virtual public float totalMass {
get { return s_unitMass * quantity; }
}
virtual public float unitMass {
get { return s_unitMass; }
}
virtual public string name {
get { return s_name; }
}
}
public class Iron : Resource {
new protected static s_unitMass = 2.0f;
new protected static s_name = "Iron";
}
这段代码非常不起作用(总是返回基类Resource的值),但是我用这种方式写出来表明我将喜欢做什么......有两个可以引用的值:
string name = Iron.GetName();
float unitMass = Iron.GetUnitMass();
和
Iron iron = new Iron();
string name = iron.name;
float unitMass = iron.unitMass;
float totalMass = iron.totalMass;
答案 0 :(得分:3)
如果这是非常,那么
// Have a [static] singleton Iron instance, but doesn't prevent
// creation of new Iron instances..
static class ResourceTable {
public static Iron Iron = new Iron();
};
// Just an Iron instance; it doesn't matter where it comes from
// (Because it is a 'singleton' the SAME instance is returned each time.)
Iron iron = ResourceTable.Iron; // or new Iron();
// [^- object ]
// .. and it can be used the same
string name = iron.name; // or ResourceTable.Iron.name, eg.
float unitMass = iron.unitMass; // [^- object too! ]
float totalMass = iron.totalMass;
现在,对于一些笔记。
一般来说,单身人士不允许&#34;替代创作方法&#34 ;;和可变的单身人士.. icky ;和,
这是类型的过度专业化(例如Iron
,Feather
,..);和,
元素类型(与特定质量相关,例如。)应该与数量分开,因为在整个问题中可能存在与资源相关联的多个数量。 / p>
考虑:
static Resource {
public string Name { get; set; }
public float UnitMass { get; set; }
}
static Bucket {
public Resource FilledWith { get; set; }
public int Quantity { get; set; }
public float TotalMass {
get { return FilledWith.UnitMass * Quantity; }
}
}
static class ResourceTable {
public Resource Iron =
new Resource { Name = "Iron", UnitMass = 1 };
public Resource Feather =
new Resource { Name = "Feather", UnitMass = 0.1 };
}
var aBucket = new Bucket {
FilledWith = ResourceTable.Iron,
Quantity = 100
};