C#属性访问器错误

时间:2009-07-21 21:01:21

标签: c#

我必须在C#2008中编写一个地址簿程序。它应该询问用户该人的姓名,电子邮件和收藏夹颜色(仅通过枚举中的颜色)。然后它应该保存联系人以供将来参考。

这是产生错误的代码。:

class Contact
{
    string Name; //This string represents the person's Name.
    string Email; //This string represents the person's Email.

    System.Drawing.KnownColor Favoritecolor
    {
        get;
    }
    static void Request()
    //  This function requests the user to type in information about the person.
    {
        Console.WriteLine("Please enter the person's name, e-mail, and favorite color");
        Console.Write; string Name; string Email; ;
        Console.ReadLine();
    }
}

错误是:

'Lab02.Program.Contact.Favoritecolor': property or indexer must have at least one accessor

3 个答案:

答案 0 :(得分:10)

 System.Drawing.KnownColor Favoritecolor
 {
     get;
     set;
 }

现在你有了一个关于FavoriteColor属性的get,但是没有设置它的位置,因此它永远不会返回实际值。

如果要实现自动属性,则需要添加一个集。否则创建一个支持字段并返回该字段。

 private System.Drawing.KnownColor _favoriteColor = someValue;
 System.Drawing.KnownColor Favoritecolor
 {
     get { return _favoriteColor; }
 }

答案 1 :(得分:2)

您的Favoritecolor属性需要同时具有get和set访问器。像这样:

System.Drawing.KnownColor Favoritecolor
        {
            get;
            set;
        }

我认为这样的事情更符合你的目标:

class Program
{
    static void Main(string[] args)
    {
        Contact contact = new Contact();

        Console.WriteLine("Please enter the person's name:");
        contact.Name = Console.ReadLine();

        Console.WriteLine("Please enter the person's e-mail address:");
        contact.Email = Console.ReadLine();

        while (contact.Favoritecolor == 0)
        {
            Console.WriteLine("Please enter the person's favorite color:");
            string tempColor = Console.ReadLine();

            try
            {
                contact.Favoritecolor = (System.Drawing.KnownColor)(Enum.Parse(typeof(System.Drawing.KnownColor), tempColor, true));
            }
            catch
            {
                Console.WriteLine("The color \"" + tempColor + "\" was not recognized. The known colors are: ");
                foreach (System.Drawing.KnownColor color in Enum.GetValues(typeof(KnownColor)))
                {
                    Console.WriteLine(color);
                }
            }
        }
    }

    class Contact
    {
        //This string represents the person's Name.
        public string Name { get; set; }

        //This string represents the person's Email.
        public string Email { get; set; } 

        public System.Drawing.KnownColor Favoritecolor
        {
            get;
            set;
        }
    }
}

您甚至不需要Color枚举,因为您使用System.Drawing.KnownColor作为属性类型。所以你可以完全理解。

答案 2 :(得分:0)

你可能想在main方法中加入一些东西,因为我们不会指向任何东西,因此当你运行app时什么都不会加载