edu*_*e05 2 c# arrays parameters
好的,我需要设计一种方法来跟踪每个项目的存在量.大约有26个项目.我还需要一种方法来确定是否存在某些项目组合.
例如,这是纸牌游戏的引擎.每张卡都有不同的类型,每张卡都可以附加卡.需要将卡片附加到卡片上以便玩家在游戏中做某些事情.为了简化这个程序,我想做点什么
if (meetsCrit(2, water, 4, ground))
{
do this()
}
else
{
displayerror()
}
Run Code Online (Sandbox Code Playgroud)
编辑:解决了!
我使用了下面几篇文章中描述的技术组合.特别提到:
Jon Skeet,Rinat Abdullin,Frank,
无论如何这里是我做的我创建了一个名为pair的类,它存储我正在寻找的类型,以及该类型的数量.然后我使用Predicate Delegate查找所有类型并计算有多少,然后我将它与我搜索的数字进行比较并分别返回true或false.
这是它的代码
public bool meetsCrit(params Pair[] specs)
{
foreach (Pair i in specs)
{
if (!(attached.FindAll(delegate(Card c) { return c.type == i.type; }).Count >= i.value))
{
return false;
}
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
Igo*_*aya 14
使用params关键字传递可变数量的参数:
private static void HowMayItems<T>(params T[] values) {
foreach (T val in values) {
//Query how many items here..
}
}
Run Code Online (Sandbox Code Playgroud)
你也可以创建一个谓词并传递一个参数过滤器.在该方法中,您可以返回所有结果的并集.像这样的东西:
public class Item {
public string Name { get; set; }
}
public class ItemFilter {
public string Name { get; set; }
public ItemFilter(string name) {
Name = name;
}
public bool FilterByName(Item i) {
return i.Name.Equals(Name);
}
}
public class ItemsTest {
private static List<Item> HowMayItems(List<Item> l,params ItemFilter[] values)
{
List<Item> results= new List<Item>();
foreach(ItemFilter f in values){
Predicate<Item> p = new Predicate<Item>(f.FilterByName);
List<Item> subList = l.FindAll(p);
results.Concat(subList);
}
return results;
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:
好的,我的混合坚果版:)怎么样:):
public enum ItemTypes{
Balloon,
Cupcake,
WaterMelon
//Add the rest of the 26 items here...
}
public class ItemFilter {
private ItemTypes Type { get; set; }
public ItemFilter(ItemTypes type) {
Type = type;
}
public bool FilterByType(ItemTypes type) {
return this.Type == type;
}
}
public class PicnicTable {
private List<ItemTypes> Items;
public PicnicTable() {
Items = new List<ItemTypes>();
}
public void AddItem(ItemTypes item) {
Items.Add(item);
}
public int HowMayItems(ItemTypes item)
{
ItemFilter filter = new ItemFilter(item);
Predicate<ItemTypes> p = new Predicate<ItemTypes>(filter.FilterByType);
List<ItemTypes> result = Items.FindAll(p);
return result.Count;
}
}
public class ItemsTest {
public static void main(string[] args) {
PicnicTable table = new PicnicTable();
table.AddItem(ItemTypes.Balloon);
table.AddItem(ItemTypes.Cupcake);
table.AddItem(ItemTypes.Balloon);
table.AddItem(ItemTypes.WaterMelon);
Console.Out.WriteLine("How Many Cupcakes?: {0}", table.HowMayItems(ItemTypes.Cupcake));
}
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 10
params数组是明显的答案.另一种方法是创建一个表示标准的类.然后,您可以使用集合初始值设定项,例如:
bool result = myCollection.Contains(new Criteria {
{ 2, Item.Balloon },
{ 4, Item.Cupcake }
});
Run Code Online (Sandbox Code Playgroud)
但如果这也没用,我们肯定需要更多信息.
如果你能提供一个例子,你想语法想调用该方法,肯定会帮助我们.
| 归档时间: |
|
| 查看次数: |
9198 次 |
| 最近记录: |