使用不同类型的键进行单字典初始化

时间:2017-07-05 11:19:35

标签: c#

有没有人像这样使用类初始化:

var dictionary = new Dictionary {
    [address] = address,
    [person] = person,
    [biz] = biz
};

如何声明使用上面的行初始化的类Dictionary, 从未在字典初始化中使用[],它将不同类型的键作为键

addresspersonbiz是不同类别地址,人物和商务的对象

参考:problem I am solving

更新

public class BaseEntity
{
    public string Id { get; set; }

    public bool Save()
    {
        return true;
    }

    public bool Delete()
    {
        return true;
    }
}

public class Address : BaseEntity
{
    public Address() { }

    public Address(string addressLine1, string addressLine2, string state, string zip)
    {
        this.AddressLine1 = addressLine1;
        this.AddressLine2 = addressLine2;
        this.State = state;
        this.ZipCode = zip;
    }

    public string AddressLine1 { get; set; }
    public string AddressLine2 { get; set; }
    public string State { get; set; }
    public string ZipCode { get; set; }

    public static Address Find(string id)
    {
        return null;
    }
}

public class Business : BaseEntity
{
    public Business() { }

    public Business(string businessName, Address address)
    {
        this.Name = businessName;
        this.Address = address;
    }

    public string Name { get; set; }
    public Address Address { get; set; }

    public static Business Find(string id)
    {
        return null;
    }
}

public class Person : BaseEntity
{
    public Person() { }

    public Person(string fname, string lname, Address address)
    {
        this.FirstName = fname;
        this.LastName = lname;
        this.Address = address;
    }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Address Address { get; set; }

    public static Person Find(string id)
    {
        return null;
    }
}

4 个答案:

答案 0 :(得分:3)

  

从未在字典初始化中使用[],它将不同类型的键作为键

索引初始化程序自C#6.0起可用

new Dictionary<int, string> { [7] = "seven" };

这使用索引器而不是Add方法,因此多次添加相同的密钥不会抛出异常,而是替换原始实例。

通过使用object来获取键和值,可以实现不同类型的支持。源中的Dictionary类型必须是这样的:

public class Dictionary : Dictionary<object, object> {}

答案 1 :(得分:1)

需要考虑的一种方法:

// Some example data of different types
var address = "";
var person = new object();
var biz = new List<int>();

var dictionary = new Dictionary<object,object> { [address] = address, [person] = person, [biz] = biz };

答案 2 :(得分:1)

如果词典需要键入类型,则可以这样做:

var dict = new Dictionary<Type, Object> {
    [typeof(Address)] = new Address(),
    [typeof(Person)] = new Person(),

    // If you have an existing object, then like this.
    [address.GetType()] = address
};

然后,读取字典的代码可以执行以下操作:

foreach (KeyValuePair<Type, Object> kv in dict) {
    var castedObject = Convert.ChangeType(kv.Value, kv.Key);        
}

答案 3 :(得分:0)

Address,Person,Biz类必须实现公共基类或接口说BaseX。键应该是一个字符串,它是派生类的名称。和

var dictionary<string, BaseX> dict = new Dictionary<string, BaseX>();
dict.Add("address", new address());
dict.Add("person", new person());
dict.Add("biz", new biz());

由于

相关问题