无法在 setter 中将类型 'Address' 隐式转换为 'String'

Cannot implicitly convert type 'Address' to 'String' in setter

如标题所示,我尝试将 setter 转换为 Adress,但出现此转换错误。 它是我的 Worker class 的代码。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace MAS_MP1
    {
        class Worker
        {
            string name, surname;
            protected string adress;
            int phoneNumber;
            string birthDate;

            Worker(String name, String surname, String adress, int phoneNumber, string birthDate)
            {
                this.name = name;
                this.surname = surname;
                this.adress = adress;
                this.phoneNumber = phoneNumber;
                this.birthDate = birthDate;

            }

           static List<Worker> list = new List<Worker>();

            public  static void add(Worker p)
            {
                list.Add(p);
            }
            public void setA(Adress a)
            {
                this.adress = a;
            }
            public static  void showExtension()


 {
            Console.WriteLine("Class Extesion");
            foreach (Worker p in list)
            {
                Console.WriteLine(p);
            }
            Console.ReadLine();

        }
        override
        public string ToString()
        {
            return "Name " + name + " Surname " + surname;
        }

        public static void Main(string[] args)
        {
            Worker p = new Worker("Tom,","Smith","NewStreet 8 London",123456,"12-12-2012");
            Adress a = new Adress("NewStreet" , 9 , "London");
            add(p);
            showExtension();


        }
    }
}

错误在这里:

public void setA(Adress a)
        {
            this.adress = a;
        }

我尝试制作一个复杂的属性,所以我只使用构造函数和 toString 覆盖方法制作第二个 class AdressAdress 获得了 street 、 homeNumber 和 cityName 属性。

这怎么可能行得通?您正在尝试将 Adress 的实例存储在字符串中...

protected string adress;

public void setA(Adress a)
{
    this.adress = a;
}

有几个修复。

您可以更改存储值的字段类型:

protected Adress adress;

并更改构造函数以接受 Adress

Worker(String name, String surname, Adress adress, int phoneNumber, string birthDate)

或者,修改您的 setter 以便存储字符串:

public void setA(Adress a)
{
    this.adress = a.ToString();
}

Grant Winney 是正确的。

此代码将不起作用,因为地址类型与 System.String 不同。尽管它们派生自 System.Object,但您不能在执行 Set 时隐式转换它。

public void setA(Adress a)
            {
                this.adress = a;
            }

您必须创建隐式转换

 public class Address{
    //other code

    public static implicit operator Adress(string a)
    {
        return new Address(){Street = a};
    }
}

勾选这个https://msdn.microsoft.com/en-us/library/z5z9kes2.aspx