我有一个具有以下型号的WebAPI:
public class Dog
{
public string name { get; set; }
public string breed { get; set; }
public string size { get; set; }
public CoatType coatType { get; set; }
private List<Dog> dogs;
}
public enum CoatType
{
Long,
Short,
Curly
};
我的存储库看起来像这样:
public class AnimalRepository
{
private const string CacheKey = "AnimalStore";
public AnimalRepository()
{
var context = HttpContext.Current;
if (context != null)
{
if (context.Cache[CacheKey] == null)
{
var contacts = new Dog[]
{
new Dog { name = "Lassie", breed = "Collie", size = "Medium", coatType = CoatType.Long },
new Dog { name = "Fido", breed = "Labrador", size = "Large" , coatType = CoatType.Short},
};
context.Cache[CacheKey] = contacts;
}
}
}
public Dog[] GetAllAnimals()
{
var context = HttpContext.Current;
if (context != null)
{
return (Dog[])context.Cache[CacheKey];
}
return new Dog[]
{
new Dog
{
name = "",
breed = "Placeholder",
size = "Placeholder",
coatType = CoatType.Curly
}
};
}
public bool SaveAnimal(Dog animal)
{
var context = HttpContext.Current;
if (context != null)
{
try
{
var currentData = ((Dog[])context.Cache[CacheKey]).ToList();
bool nameExists = false;
if (nameExists != true)
{
currentData.Add(animal);
context.Cache[CacheKey] = currentData.ToArray();
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return false;
}
}
return false;
}
}
我的控制器看起来像这样:
public class AnimalController : ApiController
{
private AnimalRepository repository;
public AnimalController()
{
this.repository = new AnimalRepository();
}
public Dog[] Get()
{
return this.repository.GetAllAnimals();
}
public HttpResponseMessage Post(Dog animal)
{
this.repository.SaveAnimal(animal);
var response = Request.CreateResponse<Dog>(System.Net.HttpStatusCode.Created, animal);
return response;
}
我的Index.cshtml看起来像这样:
<header>
<div class="content-wrapper">
<div class="float-left">
<p class="site-title">
<a href="~/">Field<b>Connect</b></a></p>
</div>
</div>
</header>
<div id="body">
<ul id="animals"></ul>
<form id="saveForm" method="post">
<h3>New Dog</h3>
<p>
<label for="name">Name:</label>
<input type="text" name="name" />
</p>
<p>
<label for="breed">Breed:</label>
<input type="text" name="breed" />
</p>
<p>
<label for="size">Size:</label>
<input type="text" name="size" />
</p>
<p>
<label for="coatType">Coat Type:</label>
<select name="coatType">
<option value="Long">Long Hair</option>
<option value="Short">Short Hair</option>
<option value="Curly">Curly Hair</option>
</select>
</p>
<input type="button" id="saveAnimal" value="Save" />
</form>
</div>
@section scripts{
<script type="text/javascript">
$(function () {
$.getJSON('/api/animal', function (contactsJsonPayload) {
$(contactsJsonPayload).each(function (i, item) {
$('#animals').append('<li>' + item.name + '</li>');
});
});
});
$('#saveAnimal').click(function () {
$.post("api/animal",
$("#saveForm").serialize(),
function (value) {
$('#animals').append('<li>' + value.name + '</li>');
},
"json"
);
});
</script>
}
所有这一切都很好。我会在我的网页上显示属于定义集合的两只狗。然而,我想要做的是在我将一只新狗保存到我要检查的集合之前,看看该狗目前是否存在于该集合中。所以我开始在代码行之后的AnimalRepository.cs中实现一个forach循环:bool nameExists = false;代码行。
// Check to see if the name of the animal already exists
for (int i = 0; i < currentData.Count; i++)
{
foreach (var item in currentData[i])
{
if (item.Equals(currentData[i].name))
{
nameExists = true;
}
}
}
但是当我构建时,我得到一个错误,我无法遍历此集合,除非我实现IEnumerable,所以我这样做了。我添加:IEnumerable到我的类继承接口,我将以下代码添加到我的Dog类,在下面完成....
public class Dog : IEnumerable<Dog>
{
public string name { get; set; }
public string breed { get; set; }
public string size { get; set; }
public CoatType coatType { get; set; }
private List<Dog> dogs;
public IEnumerator<Dog> GetEnumerator()
{
if (dogs != null)
{
foreach (Dog dog in dogs)
{
if (dog == null)
{
break;
}
yield return dog;
}
}
}
IEnumerator IEnumerable.GetEnumerator()
{
// Lets call the generic version here
return this.GetEnumerator();
}
}
public enum CoatType
{
Long,
Short,
Curly
};
但现在当我运行代码时,我看到'未定义',而不是在页面顶部看到狗的名字。我尝试返回类型字符串的IEnumerable而不是Dog但这没有帮助。我有什么想法可以解决这个问题吗?
答案 0 :(得分:0)
for (int i = 0; i < currentData.Count; i++)
{
foreach (var item in currentData[i])
{
这些是嵌套循环 - 你确定要第二个吗? currentData[i]
应该是Dog
Name
,您可以直接查看。令人困惑的部分原因是您的Dog
类本身有一个Dogs
列表 - 这几乎肯定不是您想要的。