开发者

Strange Behavior of IDictionary and Dictionary

开发者 https://www.devze.com 2023-04-04 04:03 出处:网络
I have following classes public class Person { public string FirstNa开发者_开发知识库me { get; set; }

I have following classes

public class Person
    {
        public string FirstNa开发者_开发知识库me { get; set; }
        public string LastName { get; set; }
    }

    public class Shop
    {
        public string Name { get; set; } 
    }

    public class Xyz
    {
        public string Abc { get; set; }
    }

Why is that following is not allowed

IDictionary<Person, IDictionary<Shop, Xyz>> blahItem
           = new Dictionary<Person, Dictionary<Shop, Xyz>>();


For the same reason that you can't do:

IDictionary<string, Control> dict = new Dictionary<string, Button>();

Suppose that were allowed... we could have:

Dictionary buttonDict = new Dictionary<string, Button>();
IDictionary<string, Control> controlDict = buttonDict;

controlDict["bang"] = new TextArea();
Button error = buttonDict["bang"];

Basically you'd violate type safety - IDictionary isn't covariant in either its key or value types.

Search for "generic variance" and "covariance" to find more details, including the limited support (e.g. for IEnumerable<T> which can be used safely in a covariant way) in C# 4.

0

精彩评论

暂无评论...
验证码 换一张
取 消