我正在制作一个简单的c#Web服务,该服务需要一个名称并返回相应的电话号码。
所以我创建了一个具有名称字段和数字字段的联系人类
这里
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PhoneService
{
class Contact
{
String name;
int number;
//constructor to make new contact
public Contact(String name, int number)
{
this.name = name;
this.number = number;
}
}
}
这是我的网络服务课程
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PhoneService
{
class PhoneBook : IPhoneBook
{
Contact[] contactList = new Contact[4];
//constructor
public PhoneBook ()
{
contactList[0] = new Contact("Mary Jones", 1800252525);
contactList[1] = new Contact("Bob Smith", 1800343434);
contactList[2] = new Contact("Martin Dunne", 1800797979);
contactList[3] = new Contact("Sarah Mitchel", 1800898989);
}
//method to look up name
public string lookUpNumberByName(string name)
{
//variable to hold name entered
String nameEntered = name; ;
/**
code to compare the name entered with the
the names of the contact objects.
If the name is a match with a contact name then return
the associated number
**/
//return number corresponding to the name
return null;
}
}
}
因此,我试图将4个简单的联系人对象存储在一个数组中,然后在输入名称时可以检查它是否与它们之一匹配并返回相关的电话号码。
问题出在构造函数上
我的任务是说:“让服务在内存中的集合中维护一个名称和电话号码的列表,该列表在服务类的构造函数中初始化。”
所以我不知道我应该在构造函数中包含哪些部分,而在主类中应该包含哪些部分,希望有人可以让我知道进行此操作的最佳方法。提前致谢
更新
我已经重做了我的代码,并通过删除了contact类使它变得更简单了。这里是
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PhoneService
{
class PhoneBook : IPhoneBook
{
static String[] nameList = new String[4];
static String[] numberList = new String[4];
//constructor
public PhoneBook()
{
nameList[0] = ("Mary Jones");
nameList[1] = ("Bob Smith");
nameList[2] = ("Martin Dunne");
nameList[3] = ("Martin Dunne");
numberList[0] = ("1800252525");
numberList[1] = ("1800343434");
numberList[2] = ("1800797979");
numberList[3] = ("1800898989");
}
//method to look up name
public String lookUpNumberByName(String name)
{
try
{
if (string.Equals(name, nameList[0], StringComparison.CurrentCultureIgnoreCase))
{
return numberList[0];
}
if (string.Equals(name, nameList[1], StringComparison.CurrentCultureIgnoreCase))
{
return numberList[1];
}
if (string.Equals(name, nameList[2], StringComparison.CurrentCultureIgnoreCase))
{
return numberList[2];
}
if (string.Equals(name, nameList[3], StringComparison.CurrentCultureIgnoreCase))
{
return numberList[3];
}
}
catch (System.Exception)
{
return ("That name is not found");
}
}//end of lookUpNumberByName method
}//end of class phonebook
}// end of phoneservice
我的lookUpNumberByName方法出现错误,提示并非所有代码路径都返回一个值
您基本上是在问封装问题。通常,您想考虑要公开的类的哪些部分,就像工程师考虑将汽车的哪些控制公开给驾驶员一样。基本上,如果外面没有人需要使用此方法的此属性,请不要公开它,而应保留它。
分配实际上要求您执行的操作不是公开属性,而是通过服务构造函数设置联系人列表。因此,如果您需要设置联系人列表,是否不应该将联系人列表传递到电话簿的构造函数中?请记住,您可以有多个构造函数,如果您不指定不带任何参数的构造函数,则将无法在不传递参数的情况下简单地声明该类的实例。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句